sql - 每个唯一客户 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 并将其订购数量相加?
解决方案
只是group by
和sum
:
select customerID, sum(OrderedQuantity) total_ordered
from productOrders
group by customerID
推荐阅读
- c# - 如何制作弹出警报而不是 ArgumentNullException 页面?
- python - 这是我的一个问题,因为我是编程初学者?我想问一个与Python相关的简单问题
- php - Moodle 本地插件中的 invalid_response_exception
- spring-boot - Spring Traverson 遵循相对路径忽略 baseUri
- python - 期货数据没有通过 reqHistoricalData 的权限,但 reqMktData 有效
- mysql - MySQL浮点舍入
- javascript - 罗马数字发生器
- jmeter - 比较 CPU 架构之间的应用程序性能
- python - 如何以智能的方式读取和拆分 csv 文件?
- c# - InvalidOperationException:无法解析类型“Microsoft.AspNet.Identity.RoleManager”的服务