0

产品表

ProductID   ProductDesc
401         Hotdog
402         Ham
403         Bacon

订单表

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

订单明细表

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 在每个日期以现金订购的数量,然后得到每个产品的总数?

样本输出

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
4

3 回答 3

2

利用:

GROUP BY p.ProductID, p.ProductDesc, o.OrderDate WITH ROLLUP

请参阅文档

小计行将NULL代替OrderDate. ProductID每个查询和整个查询也会有小计。HAVING您可以使用子句或调用应用程序中的代码将它们过滤掉SQL。添加到查询的末尾:

HAVING p.ProductDesc IS NOT NULL

小提琴

于 2013-09-19T01:44:41.550 回答
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
于 2013-09-19T01:37:37.097 回答
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

会给你数据。

于 2013-09-19T01:41:18.493 回答