我想要一个列显示每个类别的总和(AMOUNT)(超过90,超过60,超过30)
DECLARE @DATE VARCHAR(10)
SET @DATE='2012-12-31'
SELECT TRANDATE, TRANTYPE, INVNUM,SUM (AMOUNT), PAID, CLIENTID,
(CASE WHEN TRANDATE <= DATEADD(dd, -90, @DATE) THEN SUM(AMOUNT) END ) AS 'OVER 90',
(CASE WHEN TRANDATE<DATEADD(dd, -90, @DATE) AND TRANDATE<=DATEADD(dd, -60, @DATE) THEN SUM(AMOUNT) END) AS 'OVER 60' ,
(CASE WHEN TRANDATE<DATEADD(dd, -60, @DATE) AND TRANDATE<=DATEADD(dd, -30, @DATE) THEN SUM(AMOUNT) END)AS 'OVER 30' ,
(CASE WHEN TRANDATE<DATEADD(dd, -30, @DATE) THEN SUM(AMOUNT) END) AS 'CURRENT'
from Bill
where TRANTYPE IN ('INV', 'PAY') AND TRANDATE<=@DATE AND CLIENTID=7434
GROUP BY TRANDATE, TRANTYPE, INVNUM, PAID, CLIENTID
我该怎么办?我试过但没有真正的价值。谢谢你的评论和回答。
TRANDATE TRANTYPE INVNUM AMOUNT PAID CLIENTID OVER90 OVER60 OVER30
2012-05-06 INV 230496 7803.50 7803.50 7434 7803.50 NULL NULL
答案 0 :(得分:2)
试试这个......
DECLARE @DATE VARCHAR(10)
SET @DATE='2012-12-31'
SELECT TRANDATE, TRANTYPE, INVNUM,SUM (AMOUNT), PAID, CLIENTID,
SUM((CASE WHEN TRANDATE <= DATEADD(dd, -90, @DATE) THEN AMOUNT END )) AS 'OVER 90',
SUM((CASE WHEN TRANDATE>DATEADD(dd, -90, @DATE) AND TRANDATE<=DATEADD(dd, -60, @DATE) THEN AMOUNT END)) AS 'OVER 60' ,
SUM((CASE WHEN TRANDATE>DATEADD(dd, -60, @DATE) AND TRANDATE<=DATEADD(dd, -30, @DATE) THEN AMOUNT END))AS 'OVER 30' ,
SUM((CASE WHEN TRANDATE>DATEADD(dd, -30, @DATE) THEN AMOUNT END)) AS 'CURRENT'
from Bill
where TRANTYPE IN ('INV', 'PAY') AND TRANDATE<=@DATE AND CLIENTID=7434
GROUP BY TRANDATE, TRANTYPE, INVNUM, PAID, CLIENTID
在'CURRENT'的代码条件中,'Over 30'和'Over 60'正在检查TRANDATE&lt;这应该是TRANDATE&gt;
答案 1 :(得分:0)
将案例陈述包裹在SUM
:
DECLARE @DATE VARCHAR(10)
SET @DATE='2012-12-31'
SELECT TRANDATE, TRANTYPE, INVNUM,SUM (AMOUNT), PAID, CLIENTID,
SUM(CASE WHEN TRANDATE <= DATEADD(dd, -90, @DATE) THEN AMOUNT END ) AS 'OVER 90',
SUM(CASE WHEN TRANDATE<DATEADD(dd, -90, @DATE) AND TRANDATE<=DATEADD(dd, -60, @DATE) THEN AMOUNT END) AS 'OVER 60' ,
SUM(CASE WHEN TRANDATE<DATEADD(dd, -60, @DATE) AND TRANDATE<=DATEADD(dd, -30, @DATE) THEN AMOUNT END) AS 'OVER 30' ,
SUM(CASE WHEN TRANDATE<DATEADD(dd, -30, @DATE) THEN AMOUNT END) AS 'CURRENT'
from Bill
where TRANTYPE IN ('INV', 'PAY') AND TRANDATE<=@DATE AND CLIENTID=7434
GROUP BY TRANDATE, TRANTYPE, INVNUM, PAID, CLIENTID
答案 2 :(得分:0)
编写一个不对CASE语句进行分组的查询,以获取值为
的计算列&#39;超过90&#39;,&#39;超过60&#39;超过30&#39;超过30&#39;在它根据记录,名称列任何东西,例如MySection
然后查询并将此查询分组为一个来源的查询 - 包装您的子查询,将您的所有字段以及年龄放入主查询中
,例如
SELECT TRANDATE, TRANTYPE, INVNUM,MySection,SUM (AMOUNT), PAID, CLIENTID,
from ( ... your derived query in here..) AS DQ
where TRANTYPE IN ('INV', 'PAY') AND TRANDATE<=@DATE AND CLIENTID=7434
GROUP BY TRANDATE, TRANTYPE, INVNUM, PAID, CLIENTID, MySection