2014-01-06 31 views
-1

我正在寻找一种快速有效的方式来转换:转换行与列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.

+0

问题要求代码必须证明正在解决这个问题的一个最小的理解。包括尝试解决方案,以及为什么他们不工作。 – Kermit

+0

你应该尝试一些东西.. – Mihai

+0

我不知道从哪里开始,因此没有尝试抱歉。 – Jammy

回答

3

有几种不同的方式可以得到结果。您可以使用具有聚合函数的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 

SQL Fiddle with Demo

+0

+1这就是我认识的女孩! – Kermit

+0

无论哪种方法更有效率或没有差别? – Jammy

+0

@Jammy您将不得不测试您的系统(索引等),但与CASE _tends_进行聚合以提高效率。 – Taryn