如何在SQL中使用嵌套的Group by

时间:2016-11-06 09:10:51

标签: sql sql-server group-by

我有3个表:发票服务发票服务(参阅附图)

enter image description here

我想创建一份摘要报告,显示每项服务的每日销售额(现金总额,借记总额),我试试这个:

SELECT Service.ServiceName, SUM(ServicesinInvoice.Total) AS Total, COUNT(*) AS Count, Service.ServiceID
FROM ServicesinInvoice INNER JOIN
     Service ON ServicesinInvoice.ServiceId = Service.ServiceID INNER JOIN
     Invoice ON ServicesinInvoice.InvoiceId = Invoice.InvoiceID
WHERE (dbo.Invoice.InvoiceDate >= CONVERT(DATETIME, '2016-06-11 00:00:00', 102)) 
GROUP BY dbo.Service.ServiceName, dbo.Service.ServiceID

关于sql代码给出了每项服务的总数,我想要的是获得每项服务的现金总额和借方总额(按服务分组)。

在表格(发票)中,我有 ClientId 列,如果 ClientId = 1 ,则表示现金,否则为借方。

请帮助完成

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,可以通过条件聚合完成:

SELECT Service.ServiceID,Service.ServiceName, 
       SUM(CASE WHEN Invoice.ClientId = 1 THEN ServicesinInvoice.Total ELSE 0 END) AS Total_cash,
       SUM(CASE WHEN Invoice.ClientId <> 1 THEN ServicesinInvoice.Total ELSE 0 END) AS Total_debit,
       COUNT(*) AS Count 
FROM ServicesinInvoice INNER JOIN
     Service ON ServicesinInvoice.ServiceId = Service.ServiceID INNER JOIN
     Invoice ON ServicesinInvoice.InvoiceId = Invoice.InvoiceID
WHERE (dbo.Invoice.InvoiceDate >= CONVERT(DATETIME, '2016-06-11 00:00:00', 102)) 
GROUP BY dbo.Service.ServiceName, dbo.Service.ServiceID