有没有办法合并两行数据并保存到SQL Server中的另一个表中?
示例,我有表A(Month,Category,AmountBought),包含4行数据:
- January, Student, 30
- January, Lecturer, 40
- February, Student, 10
- February, Lecturer, 20
我想合并两个具有相同月份的行并保存到表B(Month,AmountOfStudentBought,AmountOfLecturerBought)中,如下所示:
- January, 30, 40
- February, 10, 20
答案 0 :(得分:2)
您可以使用聚合来进行旋转:
select month,
sum(case when category = 'Student' then AmountBought else 0 end) as AmountOfStudentBought,
sum(case when category = 'Lecturer' then AmountBought else 0 end) as AmountOfLecturerBought
from your_table
group by month;