我试图找到这些表格中的总销售额,首先将数量乘以商品价格,然后从这些商品的总数中找到列中所有商品的总和(ItemPrice *数量)。如果它不是很明显,我对此非常陌生。
SELECT SUM(dbo.OrderLineItems.Quantity * dbo.Products.ItemPrice) AS Total, dbo.OrdersTbl.OrderDate, SUM(Total) as SumTotal
FROM dbo.OrderLineItems INNER JOIN
dbo.Products ON dbo.OrderLineItems.ProductID = dbo.Products.ProductID INNER JOIN
dbo.OrdersTbl ON dbo.OrderLineItems.ItemID = dbo.OrdersTbl.ItemID
WHERE (dbo.OrdersTbl.OrderDate BETWEEN '2013-05-01 00:00:00' AND '2013-05-31 00:00:00')
GROUP BY dbo.OrdersTbl.OrderDate
我收到的错误是:列名无效'总计'。
不确定为什么这不起作用?任何建议将不胜感激。
似乎我没有足够的声誉来发布图片,希望这个链接就足够了。自从我创造它以来,它远非完美,而且以前从未完成过。
http://shuttergarage.com/wp-content/uploads/2014/05/ERD-Online-Store.jpg
答案 0 :(得分:0)
SELECT OrderDate,
SUM(Total) AS SumTotal
FROM
(SELECT SUM(dbo.OrderLineItems.Quantity * dbo.Products.ItemPrice) AS Total,
dbo.OrdersTbl.OrderDate AS OrderDate
FROM dbo.OrderLineItems
INNER JOIN dbo.Products ON dbo.OrderLineItems.ProductID = dbo.Products.ProductID
INNER JOIN dbo.OrdersTbl ON dbo.OrderLineItems.ItemID = dbo.OrdersTbl.ItemID
WHERE (dbo.OrdersTbl.OrderDate BETWEEN '2013-05-01 00:00:00' AND '2013-05-31 00:00:00')
GROUP BY dbo.OrdersTbl.OrderDate) As T
这样可行,但我不认为这是一个很好的处理大量数据,如果你可以发布表结构,可能对每个人都很容易。
答案 1 :(得分:0)
听起来你真的想要ROLLUP
。 The documentation当然有更多信息,但实质上它会为您生成一个包含总结果的额外行。我会像这样重写您的查询:
SELECT dbo.OrdersTbl.orderDate,
SUM(dbo.OrderLineItems.quantity * dbo.Products.itemPrice) AS total
FROM dbo.OrderLineItems
INNER JOIN dbo.Products
ON dbo.OrderLineItems.ProductID = dbo.Products.ProductID
INNER JOIN dbo.OrdersTbl
ON dbo.OrderLineItems.ItemID = dbo.OrdersTbl.ItemID
AND dbo.OrdersTbl.OrderDate >= '2013-05-01 00:00:00'
AND dbo.OrdersTbl.OrderDate < DATEADD(month, 1, '2013-05-01 00:00:00')
GROUP BY ROLLUP (dbo.OrdersTbl.OrderDate)
(未经测试,因为我无法支持) ..这应该沿着这些方向得到结果(请注意,这不包括您的来源中没有的天数!):
orderDate total
'2013-05-01' 1
'2013-05-15' 100000
'2013-05-31' 13
(null) 100014
(作为旁注,是真的dbo.OrdersTbl.ItemID
吗?我原本预计会OrderId
)