我正在寻找一种快速有效的方式来转换:转换行与列WHERE条件SQL Server 2008中
ID Type Amount
0 Damages 1
0 Other 2
1 Damages 3
1 Other 4
2 Damages 5
2 Other 6
要
ID Damages Other
0 1 2
1 3 4
2 5 6
有20万条左右表中的记录,使用SQL Server 2008.
我正在寻找一种快速有效的方式来转换:转换行与列WHERE条件SQL Server 2008中
ID Type Amount
0 Damages 1
0 Other 2
1 Damages 3
1 Other 4
2 Damages 5
2 Other 6
要
ID Damages Other
0 1 2
1 3 4
2 5 6
有20万条左右表中的记录,使用SQL Server 2008.
有几种不同的方式可以得到结果。您可以使用具有聚合函数的CASE表达式:
select id,
sum(case when type ='Damages' then amount else 0 end) damages,
sum(case when type ='Other' then amount else 0 end) other
from yourtable
group by id;
请参阅SQL Fiddle with Demo。或者因为你使用SQL Server 2008,那么你可以使用旋转功能:
select id, Damages, Other
from yourtable
pivot
(
sum(amount)
for type in (Damages, Other)
) piv
问题要求代码必须证明正在解决这个问题的一个最小的理解。包括尝试解决方案,以及为什么他们不工作。 – Kermit
你应该尝试一些东西.. – Mihai
我不知道从哪里开始,因此没有尝试抱歉。 – Jammy