我有一个如下所示的family_expenses表:
family_id bank_code amount year month
001 LB 130.00 2017 1
001 MB 200.00 2017 1
001 CB 78.00 2017 2
001 SB 69.00 2017 3
009 LB 78.00 2017 1
上表中还有其他几列。
我需要做的是获取一个家庭ID的所有记录,并将其与另一个表中的另一个子查询相结合。我使用CASE WHEN做了一些查询。
我的查询如下:
SELECT
(CASE WHEN t.rownum = 1 THEN t.bank_code ELSE '' END
) as bank_code1,
(CASE WHEN t.rownum = 1 THEN t.amount ELSE 0.00 END
) as amt1,
(CASE WHEN t.rownum = 2 THEN t.bank_code ELSE '' END
) as bank_code2,
(CASE WHEN t.rownum = 2 THEN t.amount ELSE 0.00 END
) as amt2,
(CASE WHEN t.rownum = 3 THEN t.bank_code ELSE '' END
) as bank_code3,
(CASE WHEN t.rownum = 3 THEN t.amount ELSE 0.00 END
) as amt3
FROM
(
select
ROW_NUMBER() OVER(partition by family_id Order by family_id, bank_code)
as rownum,
family_id, bank_code, AMOUNT
from family_expenses
where year = 2017 and month = 1
and family_id= 001
) t
结果显示2行记录。
bank_code1 amt1 bank_code2 amt2 bank_code3 amt3
LB 130.00
MB 200.00
如何让输出显示所有列在一行中显示结果?
预期产出:
bank_code1 amt1 bank_code2 amt2 bank_code3 amt3
LB 130.00 MB 200.00
答案 0 :(得分:1)
尝试这样(只需修改原始代码)......
IF OBJECT_ID('tempdb..#family_expenses', 'U') IS NOT NULL
DROP TABLE #family_expenses;
CREATE TABLE #family_expenses (
family_id CHAR(3) NOT NULL,
bank_code CHAR(2) NOT NULL,
amount MONEY NOT NULL,
[year] INT NOT NULL,
[month] TINYINT NOT NULL
);
INSERT #family_expenses (family_id, bank_code, amount, [year], [month]) VALUES
('001', 'LB', 130.00, 2017, 1),
('001', 'MB', 200.00, 2017, 1),
('001', 'CB', 78.00, 2017, 2),
('001', 'SB', 69.00, 2017, 3),
('009', 'LB', 78.00, 2017, 1);
SELECT
t.family_id,
bank_code1 = MAX(CASE WHEN t.rownum = 1 THEN t.bank_code END ),
amt1 = SUM(CASE WHEN t.rownum = 1 THEN t.amount END),
bank_code2 = MAX(CASE WHEN t.rownum = 2 THEN t.bank_code END ),
amt2 = SUM(CASE WHEN t.rownum = 2 THEN t.amount END ),
bank_code3 = MAX(CASE WHEN t.rownum = 3 THEN t.bank_code END ),
amt3 = SUM(CASE WHEN t.rownum = 3 THEN t.amount ELSE 0.00 END )
FROM
(
SELECT
rownum = ROW_NUMBER() OVER (PARTITION BY fe.family_id ORDER BY fe.family_id, fe.bank_code ),
fe.family_id,
fe.bank_code,
fe.amount
FROM
#family_expenses fe
WHERE
fe.year = 2017
AND fe.month = 1
AND fe.family_id = '001'
) t
GROUP BY
t.family_id;
结果...
family_id bank_code1 amt1 bank_code2 amt2 bank_code3 amt3
--------- ---------- --------------------- ---------- --------------------- ---------- ---------------------------------------
001 LB 130.00 MB 200.00 NULL 0.0000