按字段删除组

时间:2013-06-28 16:13:22

标签: group-by db2

从DB2获取数据时遇到了问题。我想按客户汇总发票金额。在一个领域,(计算 - 我称之为InvoicedThisYear)它计算出今年开发票的数量,而在另一个领域,它计算出前一年的发票(计算,我称之为InvoicedLastYear)。然而,由于它是summariesed我已经由Cust分组,但它也想要由InvoiceYear分组的数据,所以我必须将其包括在分组中。我的问题在于我的结果我现在已经零了多年,没有数据和重复,例如:

Cust     InvoicedThisYear   InvoiceLastYear
abc          0                 100
abc          100                0

理想情况下,我希望看到

Cust   InvoicedThisYear     InvoicedLastYear
abc        100                  100

这是我的代码:

SELECT 
   Cust AS Customer,
   (CASE WHEN InvoiceYear = Year(Current Date) THEN sum(InvoiceAmt)ELSE 0 END) as InvoicedThisYear,
   (CASE WHEN InvoiceYear = year(Current Date)-1 THEN sum(InvoiceAmt)ELSE 0 END) as InvoicedLastYear
FROM 
    InvHead
GROUP BY 
   Cust, 
   InvoiceYear
HAVING
   ((CASE WHEN InvoiceYear = Year(Current Date) THEN sum(InvoiceAmt)ELSE 0 END)<>0)
   OR
   ((CASE WHEN InvoiceYear = year(Current Date)-1 THEN sum(InvoiceAmt)ELSE 0 END)<>0)
ORDER BY 
   Cust

如何获得所需的结果?如果我删除grouptimes Invoice Year

,查询将不会运行

作为大小说明,它可以在MS Access中使用而无需按发票年分组!

谢谢,

迈克尔

1 个答案:

答案 0 :(得分:3)

您需要将SUM()放在案例陈述周围:

SELECT 
   Cust AS Customer,
   sum(CASE WHEN InvoiceYear = Year(Current Date) THEN InvoiceAmt ELSE 0 END) as InvoicedThisYear,
   sum(CASE WHEN InvoiceYear = year(Current Date)-1 THEN InvoiceAmt ELSE 0 END) as InvoicedLastYear
FROM 
    InvHead
GROUP BY 
   Cust
ORDER BY 
   Cust