大家好,
請教大家有個sql有12個月(01、02、03.....、10、11、12)要寫12個SQL指令, 有辦法改寫成1個SQL嗎?
select
no,
01 as 月,
SUM(CASE WHEN SUBSTRING([type_order], 1, 1) = 'a' THEN money01 ELSE 0 END) AS 月收入
from a
GROUP BY no
UNION
select
no,
02 as 月,
SUM(CASE WHEN SUBSTRING([type_order], 1, 1) = 'a' THEN money02 ELSE 0 END) AS 月收入
from a
GROUP BY no
.
.
.
UNION
select
no,
12 as 月,
SUM(CASE WHEN SUBSTRING([type_order], 1, 1) = 'a' THEN money12 ELSE 0 END) AS 月收入
from a
GROUP BY no
Oracle Row to Column 函式介紹
這是你要的嗎?
還有你要用SQL Fiddle填寫資料,別人才會更快回覆你。
用一句 MS SQL指令解決的方法如下,E_date 是日期欄位,@year 是 年(4位) @ym 是 年月(2+2位):
declare @year varchar(8) = '2022', @ym varchar(8) = 'ALL';
select no, FORMAT(E_date,'yyMM') 月, SUM(CASE WHEN SUBSTRING([type_order], 1, 1) = 'a' THEN money+FORMAT(E_date,'MM') ELSE 0 END) AS 月收入 from a WHERE FORMAT(E_date,'yyyy')=@year and ( @ym='ALL' OR FORMAT(E_date,'yyMM')=@ym ) GROUP BY no, FORMAT(E_date,'yyMM') ORDER BY no, FORMAT(E_date,'yyMM')
謝謝您的回覆
我的Table沒有日期欄位, 要怎麼改寫呢?
補充說明:
月要呈現01、02、03....10、11、12
下面的sum的money欄位也要隨之變為
money01、money02、money03、...money10、money11、money12
如
SUM(CASE WHEN SUBSTRING([type_order], 1, 1) = 'a' THEN money01 ELSE 0 END) AS 月收入
SUM(CASE WHEN SUBSTRING([type_order], 1, 1) = 'a' THEN money02 ELSE 0 END) AS 月收入
SUM(CASE WHEN SUBSTRING([type_order], 1, 1) = 'a' THEN money03 ELSE 0 END) AS 月收入
SUM(CASE WHEN SUBSTRING([type_order], 1, 1) = 'a' THEN money10 ELSE 0 END) AS 月收入
....
CREATE TABLE MM (
TYPE_ORDER VARCHAR(10),
MONEY01 INT,
MONEY02 INT,
MONEY03 INT,
MONEY04 INT,
MONEY05 INT,
);
INSERT INTO MM VALUES
('A11',11,22,33,44,55),
('B22',22,33,44,55,66),
('A33',33,44,55,66,77),
('C44',44,55,66,77,88);
WITH CTE_01 AS (
SELECT TYPE_ORDER,QTY,MONEY FROM
(SELECT TYPE_ORDER,MONEY01,MONEY02,MONEY03,MONEY04,MONEY05 FROM MM) AS A
UNPIVOT(QTY FOR MONEY IN (MONEY01,MONEY02,MONEY03,MONEY04,MONEY05)) AS B
)
SELECT MONTH,SUM(QTY) AS QTY
FROM
(SELECT RIGHT(MONEY,2) AS 'MONTH',*
FROM CTE_01
WHERE LEFT(TYPE_ORDER,1) = 'A') AS C
GROUP BY MONTH
Pivot 語法彙總SELECT結果的轉置
https://coolmandiary.blogspot.com/2021/08/t-sql22pivot-select.html