日期:2014-05-18  浏览次数:20550 次

数据行列转换的问题
select   [类别],[满意度],Cast(Datepart(year,fwrq)   As   Varchar)+Cast(Datepart(month,fwrq)   As   Varchar),Count(*)   As   StatCount  

From   vCust  

Where   Type   IN   ( '1 ', '2 ', '3 ')  

Group   By   [类别],[满意度],Cast(Datepart(year,fwrq)   As   Varchar)+Cast(Datepart(month,fwrq)   As   Varchar)

得到如下结果:
[类别]       [满意度]   [月份]       [数量]  
大客户 3 20078 1
普通客户 1 20078 2
VIP会员 2 20078 1

现在我想转换成
[类别]   [月份]   [满意]   [基本满意]   [不满意]   [数量]

需要什么改SQL呢
就是把   满意度   总的有三种情况,把行转成列



------解决方案--------------------
try

Select
类别,
Convert(Varchar(7), fwrq, 120) As 月份,
SUM(Case 满意度 When N '满意 ' Then 1 Else 0 End) As 满意数量,
SUM(Case 满意度 When N '基本满意 ' Then 1 Else 0 End) As 基本满意数量,
SUM(Case 满意度 When N '不满意 ' Then 1 Else 0 End) As 不满意数量
From
vCust
Where
Type IN ( '1 ', '2 ', '3 ')
Group By
类别,
Convert(Varchar(7), fwrq, 120)
------解决方案--------------------
select [类别]
,case [满意度] when 3 then '满意 ' as 满意
,case [满意度] when 2 then '基本满意 ' as 基本满意
,case [满意度] when 1 then '不满意 ' as 不满意
,Cast(Datepart(year,fwrq) As Varchar)+Cast(Datepart(month,fwrq) As Varchar),Count(*) As StatCount

From vCust

Where Type IN ( '1 ', '2 ', '3 ')

Group By [类别],[满意度],Cast(Datepart(year,fwrq) As Varchar)+Cast(Datepart(month,fwrq) As Varchar)
------解决方案--------------------
select 类别,convert(varchar(6),fwrq,112),
sum(case 满意度 when 1 then 1 else 0 end) 满意,
sum(case 满意度 when 2 then 1 else 0 end) 基本满意,
sum(case 满意度 when 3 then 1 else 0 end) 不满意
from vCust group by 类别,convert(varchar(6),fwrq,112)
------解决方案--------------------
--这样吧

Select
类别,
Convert(Varchar(7), fwrq, 120) As 月份,
SUM(Case 满意度 When 1 Then 数量 Else 0 End) As 满意数量,
SUM(Case 满意度 When 2 Then 数量 Else 0 End) As 基本满意数量,
SUM(Case 满意度 When 3 Then 数量 Else 0 End) As 不满意数量
From
vCust
Where
Type IN ( '1 ', '2 ', '3 ')
Group By
类别,
Convert(Varchar(7), fwrq, 120)