2

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

  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 的情况下修改查询以重新运行结果,如下所示。 查询结果

4

1 回答 1

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
于 2013-08-26T10:14:12.590 回答