TSQL将字段值放入列

时间:2017-07-31 15:44:10

标签: sql-server tsql devexpress

我正在尝试对数据库进行查询以使用我提取的数据构建图表(使用Developer Express)。 所以我有这张桌子,我回到了现在的状态:

enter image description here

但我想要做的是让数据为MYCOUNT的所有实例提取字段值,并将它们转换为自己的填充列,如下所示:

enter image description here

这是查询的代码:

SELECT  
    'Approval Progress' AS ACTIVITY, 
    CASE STATUS 
       WHEN 0 THEN 'NO ACTION' 
       WHEN 1 THEN 'PENDING' 
       WHEN 2 THEN 'APPROVED' 
       WHEN 3 THEN 'REJECTED'
       ELSE 'ERROR' 
    END AS APRV, 
    COUNT(*) AS MYCOUNT,  
    4 AS TOT0, 8 AS TOT1, 3 AS TOT2 
FROM 
    IT_PROJAPPROVEWIP AS IT_PROJAPPROVEWIP_1 
GROUP BY 
    STATUS

谢谢!

1 个答案:

答案 0 :(得分:1)

一种方法是在每个状态上使用交叉连接:

SELECT *
FROM
  (SELECT 'Approval Progress' AS ACTIVITY,
          CASE STATUS
              WHEN 0 THEN 'NO ACTION'
              WHEN 1 THEN 'PENDING'
              WHEN 2 THEN 'APPROVED'
              WHEN 3 THEN 'REJECTED'
              ELSE 'ERROR'
          END AS APRV,
          COUNT(*) AS MYCOUNT
   FROM IT_PROJAPPROVEWIP AS IT_PROJAPPROVEWIP_1
   GROUP BY STATUS)a
CROSS JOIN
  (SELECT COUNT(*) AS Tot0
   FROM IT_PROJAPPROVEWIP
   WHERE STATUS = 0 ) b
CROSS JOIN
  (SELECT COUNT(*) AS Tot1
   FROM IT_PROJAPPROVEWIP
   WHERE STATUS = 1 ) c
CROSS JOIN
  (SELECT COUNT(*) AS Tot2
   FROM IT_PROJAPPROVEWIP
   WHERE STATUS = 2 ) d
CROSS JOIN
  (SELECT COUNT(*) AS Tot3
   FROM IT_PROJAPPROVEWIP
   WHERE STATUS = 3 ) e