我有两个品牌brand1
和brand2
我正在寻找每个品牌的每小时销售量。
我尝试使用以下查询执行此操作,但它返回以下输出:
查询
WITH MyGroupCte
AS (SELECT
OrderDate,
Brands.BrandID,
Brands.BrandName,
SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge - ((SUM((OrderDetails.Quantity * OrderDetails.UnitPrice))) * Orders.Discount / 100) AS Amount,
COUNT(Orders.OrderID) AS Orders
FROM dbo.Orders
INNER JOIN dbo.Outlets
ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.OrderDetails
ON dbo.OrderDetails.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Brands
ON dbo.Brands.BrandID = dbo.Outlets.BrandID
WHERE dbo.Orders.OrderStatus = 'Closed'
AND dbo.Orders.OrderDate BETWEEN '06/May/2017 14:00:00.000' AND '06/May/2017 16:00:00.000'
GROUP BY Orders.OrderID,
dbo.Orders.DeliveryCharge,
Orders.Discount,
Brands.BrandID,
Brands.BrandName,
Orders.OrderDate)
SELECT
BrandName AS Brand,
OrderDate as [Date-Time],
COUNT(Orders) AS Orders,
SUM(Amount) AS Amount
FROM MyGroupCte
GROUP BY OrderDate,
BrandName
ORDER BY Amount DESC
输出
Brand Date-Time Orders Amount
brand1 2017-05-06 14:04:52.000 1 530.00
brand1 2017-05-06 14:05:06.000 1 448.00
brand2 2017-05-06 15:27:21.000 1 347.00
brand2 2017-05-06 15:52:25.000 1 254.00
brand2 2017-05-06 16:06:25.000 1 100.00
而不是我正在寻找下面格式的输出
Brand Date-Time Orders Amount
brand1 2017-05-06 14:00:00.000 2 978.00
brand2 2017-05-06 15:00:00.000 2 601.00
brand2 2017-05-06 16:00:00.000 2 100.00
答案 0 :(得分:3)
使用DATEADD(hour, DATEDIFF(hour, 0, OrderDate), 0)
将日期时间截断为小时,并将其用于分组。
SELECT
BrandName AS Brand,
DATEADD(hour, DATEDIFF(hour, 0, OrderDate), 0) as [Date-Time],
COUNT(Orders) AS Orders,
SUM(Amount) AS Amount
FROM MyGroupCte
GROUP BY BrandName, DATEADD(hour, DATEDIFF(hour, 0, OrderDate), 0)