SQL - CASE WHEN查询

时间:2017-01-15 23:51:03

标签: sql sum case having

我试图从我的表中获取为过去12个月内花费超过1000的客户提供的所有发票。以下是我的表格,仅供两位客户使用:

enter image description here

我的疑问:

SELECT 
    t.Customer, t.Invoice 
FROM 
    (SELECT
         CI.Customer, CI.Invoice, CI.Date,
         SUM(CASE 
                WHEN CI.Date > DATEADD(month, -12, getdate()) 
                   THEN CI.Valuee 
                ELSE 0 
             END) as Net
     FROM 
         CustomerInvoice CI
     GROUP BY 
         CI.Customer, CISRV.Invoice, CISRV.Date) AS t
GROUP BY 
    t.Customer, t.Invoice
HAVING 
   SUM (t.Net) > 1000

结果我将只收到INV-341453发票,但我想同时显示发票INV-346218和INV-349065。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

使用ANSI标准窗口函数:

select ci.*
from (select ci.*,
             sum(ci.value) over (partition by ci.customer) as total_value
      from CustomerInvoice CI
      where CI.Date > DATEADD(month, -12, getdate())
     ) ci
where total_value > 1000;

通过“所有发票”,我认为你的意思是过去12个月的那些。

答案 1 :(得分:0)

您可以使用分组查询来识别超过1000阈值的客户,然后显示这些客户的所有发票:

SELECT Customer, Invoice 
 FROM CustomerInvoice 
 WHERE Customer IN 
     (SELECT Customer 
     FROM CustomerInvoice
     GROUP BY Customer
     HAVING SUM(CASE WHEN CI.Date>DATEADD(month,-12,getdate()) THEN CI.Valuee ELSE 0 END) > 1000)