查询以在不使用PIVOT的情况下将行创建为列值

时间:2013-08-26 10:08:48

标签: sql-server tsql

我有以下查询,并给出了如下所示的结果。

  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'

Query result

如何在不使用PIVOT重新运行结果的情况下修改查询,如下所示。    Query Result

1 个答案:

答案 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