我想按照下面的方式對我的工作站代碼進行分組,但是我的結果集會不斷輸出所有內容,並且會多次輸出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
等一下,您使用的是什麼RDBMS?,您的第二個CTE如何不使用「GROUP BY」而使用聚合函數? – Lamak
對不起,只是做了一個編輯它我忘了複製該部分..我正在使用Microsoft SQL Server – ltsai