这样的视图如何实现?
现在表table中有这样的数据
cardno typeid num
123 1 100
123 2 10
123 3 1
122 1 50
122 2 10
122 3 5
把上列结构变成
catdno type1 type2 type3
123 100 10 1
122 50 10 5
通常这样的转换怎么做?
------解决方案----------------------如果typeid是固定的
Select
cardno,
SUM(Case typeid When 1 Then num Else 0 End) As type1,
SUM(Case typeid When 2 Then num Else 0 End) As type2,
SUM(Case typeid When 3 Then num Else 0 End) As type3
From
[table]
Group By
cardno
--如果typeid不是固定的
Declare @S Varchar(8000)
Select @S = 'Select cardno '
Select @S = @S + ', SUM(Case typeid When ' + Cast(typeid As Varchar) + ' Then num Else 0 End) As type ' + Cast(typeid As Varchar)
From [table] Group By typeid
Select @S = @S + ' From [table] Group By cardno '
EXEC(@S)