我使用以下查询根据单个条件计算特定列数据。
SELECT COUNT(DISTINCT(S.INVOICENO)) AS LESSTWO , YEAR(S.invoicedate) YER,
Month(S.invoicedate) MNTH
FROM SALESDATA S
where S.BILLINGTYPE='INVOICE'
AND (S.invoicedate >='4-1-2009' and S.invoicedate <='4-30-2010')
AND S.TAXABLEAMT <=2000
GROUP BY YEAR(S.invoicedate) ,Month(S.invoicedate)
ORDER BY YEAR(S.invoicedate) ,Month(S.invoicedate)
但是我必须再计算3个条件。是否有可能根据3个条件(即2001 - 3000,3001 - 4000,4001 - 5000,> 5000)计算,我想要所有条件的结果集?
此致
N.SRIRAM
答案 0 :(得分:0)
我认为你真的需要将查询分成3个不同的查询 - 每个查询需要一个
答案 1 :(得分:0)
未经测试,但应该是正确的:
SELECT CASE
WHEN S.TaxableAmt <= 2000 THEN '<=2000'
WHEN S.TaxableAmt <= 3000 THEN '2001-3000'
WHEN S.TaxableAmt <= 4000 THEN '3001-4000'
ELSE '>5000'
END as Bracket,
COUNT(DISTINCT(S.INVOICENO)) AS LESSTWO , YEAR(S.invoicedate) YER,
Month(S.invoicedate) MNTH
FROM SALESDATA S
where S.BILLINGTYPE='INVOICE'
AND (S.invoicedate >='20090401' and S.invoicedate <='20100430')
GROUP BY
CASE
WHEN S.TaxableAmt <= 2000 THEN '<=2000'
WHEN S.TaxableAmt <= 3000 THEN '2001-3000'
WHEN S.TaxableAmt <= 4000 THEN '3001-4000'
ELSE '>5000'
END,
YEAR(S.invoicedate) ,Month(S.invoicedate)
ORDER BY YEAR(S.invoicedate) ,Month(S.invoicedate)
你必须在GROUP BY
子句中重复case表达式(或者将它全部放在子查询中),并且我已经修复了你的日期常量,以便它们是明确的。