我有以下查询,并给出了如下所示的结果。
SELECT
SUM(atm) atm,SUM(cc) cc,SUM(csh) csh ,SUM(chk) chk
FROM sales
WHERE repId= 9000
AND DATEADD(dd,0,DATEDIFF(dd,0,idate)) ='2013-08-25 00:00:00'
如何在不使用PIVOT重新运行结果的情况下修改查询,如下所示。
答案 0 :(得分:2)
这应该有效
SELECT 'atm' type, SUM(atm) Amount FROM sales
WHERE repId= 9000 AND DATEADD(dd,0,DATEDIFF(dd,0,idate)) ='2013-08-25 00:00:00'
UNION ALL
SELECT 'cc' type, SUM(cc) Amount FROM sales
WHERE repId= 9000 AND DATEADD(dd,0,DATEDIFF(dd,0,idate)) ='2013-08-25 00:00:00'
UNION ALL
SELECT 'csh' type, SUM(csh) Amount FROM sales
WHERE repId= 9000 AND DATEADD(dd,0,DATEDIFF(dd,0,idate)) ='2013-08-25 00:00:00'
UNION ALL
SELECT 'chk' type, SUM(chk) Amount FROM sales
WHERE repId= 9000 AND DATEADD(dd,0,DATEDIFF(dd,0,idate)) ='2013-08-25 00:00:00'
或者,使用CTE:
;WITH CTE(atm,cc,csh,chk) AS
(SELECT SUM(atm),SUM(cc),SUM(csh),SUM(chk) FROM sales
WHERE repId= 9000 AND DATEADD(dd,0,DATEDIFF(dd,0,idate)) ='2013-08-25 00:00:00' )
SELECT 'atm' Type,atm Amount FROM CTE
UNION ALL SELECT 'cc' ,cc FROM CTE
UNION ALL SELECT 'csh',csh FROM CTE
UNION ALL SELECT 'chk',chk FROM CTE