2014-01-22 118 views
0

我想按照下面的方式對我的工作站代碼進行分組,但是我的結果集會不斷輸出所有內容,並且會多次輸出others。我想通過我的別名將所有內容分組,但是對於我的工作站others,它似乎並不像是對它進行分組。按別名分組

WITH 
     station as (
     SELECT 
     CASE 
      WHEN t.station='AB' THEN 'AB' 
      WHEN t.station='AS' THEN 'AS' 
      WHEN t.station='KF' THEN 'KF' 
      WHEN t.station='PR' THEN 'PR' 
      WHEN t.station='SV' THEN 'SV' 
      WHEN t.station='RE' THEN 'RE' 
      WHEN t.station='TVR' OR t.station='TDT' THEN 'TDT' 
      ELSE 'Others' 
     END AS 'station' 
     FROM t 

    ) 
     porders as (
     SELECT 
     CASE 
      WHEN t.station='AB' THEN 'AB' 
      WHEN t.station='AS' THEN 'AS' 
      WHEN t.station='KF' THEN 'KF' 
      WHEN t.station='PR' THEN 'PR' 
      WHEN t.station='SV' THEN 'SV' 
      WHEN t.station='RE' THEN 'RE' 
      WHEN t.station='TVR' OR t.station='TDT' THEN 'TDT' 
      ELSE 'Others' 
     END AS 'station', 
     COUNT(*) AS 'p_orders' 
     FROM a, t, v, station 
     WHERE a.psn = t.psn 
      AND t.highest_psn = 0 
      AND v.detailno_i = a.detailno_i 
      AND t.station!='' 
      AND a.status=1 
      AND v.order_type='P' 
      GROUP BY t.station 

) 
     SELECT station.station, porders.p_orders 
     FROM station join porders on(station.station=porders.station) 

輸出

station|porders 
--------------- 
AB  2 
AS  4 
KF  3 
PR  10 
SV  2 
RE  20 
TDT  10 
Others 1 
Others 2 
Others 3 

所需的輸出:

station|porders 
--------------- 
AB  2 
AS  4 
KF  3 
PR  10 
SV  2 
RE  20 
TDT  10 
Others 6 
+2

等一下,您使用的是什麼RDBMS?,您的第二個CTE如何不使用「GROUP BY」而使用聚合函數? – Lamak

+0

對不起,只是做了一個編輯它我忘了複製該部分..我正在使用Microsoft SQL Server – ltsai

回答

2

您得到的結果是因爲您有三個t.station值映射到Other這一事實GROUP BY t.station並不關心他們在您的選擇中預計到Other

爲了解決這個問題,你用你的情況,而不是翻譯值t.station

GROUP BY 
     CASE 
      WHEN t.station='AB' THEN 'AB' 
      WHEN t.station='AS' THEN 'AS' 
      WHEN t.station='KF' THEN 'KF' 
      WHEN t.station='PR' THEN 'PR' 
      WHEN t.station='SV' THEN 'SV' 
      WHEN t.station='RE' THEN 'RE' 
      WHEN t.station='TVR' OR t.station='TDT' THEN 'TDT' 
      ELSE 'Others' 
     END 
+0

哇不知道我可以做到這一點..非常感謝你! – ltsai

0

爲了您的最後兩行,怎麼樣:

SELECT station.station, SUM(porders.p_orders) as tot_porders 
FROM station join porders on(station.station=porders.station) 
GROUP BY station.station 
2

需要組這不是一個答案,只是一個註釋,您可以簡化您的情況陳述了很多:

CASE WHEN t.station in ('AB', 'AS', 'KF', 'PR', 'SV', 'RE') THEN t.station 
     WHEN t.station in ('TVR', 'TDT') THEN 'TDT' 
     ELSE 'Others' 
    END 
+0

謝謝你的提示!我發現這非常有用:) – ltsai