数据库中的表格就像这种格式
id Name Month Spending
1001 Murphy JAN 500
1001 Murphy FEB 750
1001 Murphy MAR 300
1002 Patterson JAN 155
1002 Patterson FEB 85
1002 Patterson MAR 60
1003 Firrelli JAN 125
1003 Firrelli FEB 100
1003 Firrelli MAR 250
对于图中的绘图数据,我需要像这样的查询结果..
id name JAN FEB MAR
1001 Murphy 500 750 300
1002 Patterson 155 85 60
1003 Firrelli 125 100 250
是否可以获得这样的查询结果?
无需创建表,只需查询结果。
答案 0 :(得分:3)
使用Conditional Aggregate
将行转置为列。试试这个。
select id,Name,
max(case when Month ='Jan' then Spending end) Jan,
max(case when Month ='Feb' then Spending end) Feb,
max(case when Month ='Mar' then Spending end) Mar
from yourtable
group by id,Name
答案 1 :(得分:0)
如果月数是静态的,可以通过多种方式完成,例如:
SELECT id, Name, SUM(JAN) AS JAN, SUM(FEB) AS FEB, SUM(MAR) AS MAR
FROM
(SELECT id, name, Spending AS JAN, 0 AS FEB, 0 AS MAR
FROM t1
WHERE Month = 'JAN'
UNION ALL
SELECT id, name, 0, Spending, 0
FROM t1
WHERE Month = 'FEB'
UNION ALL
SELECT id, name, 0, 0, Spending
FROM t1
WHERE Month = 'MAR')
GROUP BY id, Name