2017-07-31 125 views
0

我想在數據庫上執行一個查詢來構建與我拉(使用Developer Express)的數據的圖表。 所以我有這個表,我回去跟我目前有:TSQL使字段值成列

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

請編寫代碼和預期產出/投入的,而不是指圖像 – yanman1234

+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 
+0

這正是我所尋找的,但經過大約2個小時的谷歌搜索後,我找不到任何東西。謝謝!你能解釋一下你做了什麼,所以我可以自己學習如何做到這一點? –

+0

基本上,它計算子查詢中每個狀態ID的計數,然後使用交叉連接將它們連接到原始數據集。您可以在http://www.w3resource.com/sql/joins/cross-join.php閱讀更多關於交叉連接的信息。 –