首页 > 解决方案 > 每个唯一客户 ID 的总数量

问题描述

我正在尝试编写一个查询,该查询返回每个客户订购的产品总量。并将总和返回为“Total Ordered”并返回客户的 ID。

这是表格数据,如果您需要任何其他表格,请告诉我。


CREATE TABLE dbo.ProductOrders
    (
        POID INT NOT NULL IDENTITY(1, 1) PRIMARY KEY ,
        ProductId INT NOT NULL
            CONSTRAINT FK_ProductOrders_ProductId_ref_Products_ProductId
            FOREIGN KEY REFERENCES dbo.Products ( ProductId ) ,
        CustomerId INT NOT NULL ,
        OrderedQuantity INT ,
        Filled BIT NOT NULL
            CONSTRAINT DF_ProductOrders_Filled
                DEFAULT ( 0 ) ,
        DateOrdered DATETIME
            CONSTRAINT DF_ProductOrders_DateOrdered
                DEFAULT ( GETDATE()) ,
        DateFilled DATETIME
            CONSTRAINT DF_ProductOrders_DateFilled
                DEFAULT ( GETDATE())
    );

INSERT dbo.ProductOrders ( ProductId ,
                           CustomerId ,
                           OrderedQuantity ,
                           Filled ,
                           DateOrdered ,
                           DateFilled )
VALUES ( 2, 1, 1000, 0, '4/16/18 8:09:13', NULL ) ,
       ( 2, 1, 500, 1, '3/27/18 17:00:21', '6/24/18 13:29:01' ) ,
       ( 3, 3, 2000, 1, '12/01/04 13:28:58', '2/19/05 19:41:42' ) ,
       ( 1, 1, 632, 0, '5/23/18 4:25:52', NULL ) ,
       ( 4, 4, 901, 0, '3/30/18 21:30:28', NULL );

这是我迄今为止尝试过的,但我不确定如何选择多次出现的订购数量并将它们放在总和列中。

select customerID, OrderedQuantity
from productOrders

此查询显示所有已下订单的客户,并且有一些重复出现的客户 ID 具有不同的订单数量。我将如何仅显示唯一的客户 ID 并将其订购数量相加?

标签: sqlsql-serversumaggregate-functions

解决方案


只是group bysum

select customerID, sum(OrderedQuantity) total_ordered
from productOrders
group by customerID

推荐阅读