2计入1个sql

时间:2013-09-19 01:34:34

标签: sql tsql sql-server-2008-r2

的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

3 个答案:

答案 0 :(得分:2)

使用:

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

请参阅Documentation

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

HAVING p.ProductDesc IS NOT NULL

FIDDLE

答案 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

会为您提供数据。