的productTable
ProductID ProductDesc
401 Hotdog
402 Ham
403 Bacon
OrderTable
OrderID OrderPayment NumOrder OrderDate
5001 Cash 3 9-15-2013
5002 Credit 2 9-16-2013
5003 Credit 2 9-17-2013
5004 Cash 3 9-18-2013
OrderDetailsTable
OrderDetailsID OrderID ProductID
70001 5001 401 -
70002 5001 401 -
70003 5001 403 -
70004 5002 401
70005 5002 402
70006 5003 402
70007 5003 403
70008 5004 403 -
70009 5004 402 -
70010 5004 401 -
我将如何计算每个日期以现金订购的产品数量,然后获取每种产品的总数?
示例输出
ProductID ProductDesc CountOnCash OrderDate
401 Hotdog 2 9-15-2013
401 Hotdog 1 9-18-2013
401 Hotdog 3 ---------
402 Ham 1 9-18-2013
402 Ham 1 ---------
403 Bacon 1 9-15-2013
403 Bacon 1 9-18-2013
403 Bacon 2 ---------
Select p.ProductID, p.ProductDesc, count(p.ProductId) as NumOrder, o.OrderDate
from Product p
inner join OrderDetails od on p.productid = od.productid
inner join Order o on o.orderid = od.orderid
where orderpayment = 'cash'
Group by p.ProductID, p.ProductDesc, o.OrderDate
答案 0 :(得分:2)
使用:
GROUP BY p.ProductID, p.ProductDesc, o.OrderDate WITH ROLLUP
小计行将NULL
代替OrderDate
。每个ProductID
和整个查询都会有小计。您可以使用HAVING
子句或使用SQL
调用的应用程序中的代码来过滤掉这些内容。添加到查询的末尾:
HAVING p.ProductDesc IS NOT NULL
答案 1 :(得分:1)
您需要条件求和,因此将条件从where
子句移到case
语句:
Select p.ProductID, p.ProductDesc,
sum(case when orderpayment = 'cash' then 1 else 0 end) as NumCash,
count(*) as NumOrder, o.OrderDate
from Product p
inner join OrderDetails od on p.productid = od.productid
inner join Order o on o.orderid = od.orderid
Group by p.ProductID, p.ProductDesc, o.OrderDate
答案 2 :(得分:1)
据我了解,你想要小计。
Select p.ProductID, p.ProductDesc, count(p.ProductId) as NumOrder, o.OrderDate
from Product p
inner join OrderDetails od on p.productid = od.productid
inner join Order o on o.orderid = od.orderid
where orderpayment = 'cash'
Group by p.ProductID, p.ProductDesc, o.OrderDate
Union
Select p.ProductID, p.ProductDesc, count(p.ProductId) as NumOrder, '------'
from Product p
inner join OrderDetails od on p.productid = od.productid
inner join Order o on o.orderid = od.orderid
where orderpayment = 'cash'
Group by p.ProductID, p.ProductDesc
会为您提供数据。