表A
id usersid status
1 1 0
2 1 1
3 1 2
4 1 0
5 1 2
6 2 0
7 2 1
8 2 2
9 2 0
SQL语句查询出来显示如下:
usersid status0 status1 status 2
1 2 1 2
2 2 1 1
select userid,count([0]) as status0,count([1]) as status1,count([2]) as status2
from A
PIVOT
(
max(id) for status in ([0],[1],[2])
) B
group by userid
自己运行一下,我没运行过了 呵呵
交叉表!
CREATE TABLE #t
这是刚用过的一个类似功能实现
temp1
(
cust_survey_id INT,
item VARCHAR(300),
da INT
)
INSERT INTO #temp1 SELECT...............................
--拼接sql产生交叉结果的sql语句
declare @sql varchar(8000) set @sql = 'select cust_survey_id,'
select @sql = @sql + 'sum(case item when '''+Convert(varchar(10),item)+''' then da else 0 end) as '''+Convert(varchar(10),item)+''','
from (select distinct item from #temp1) as a
--PRINT @sql
select @sql = left(@sql,len(@sql)-1) + ' from #temp1 group by cust_survey_id'
PRINT @sql
exec(@sql)
GO
拼接的结果应该是
select sum(case usersid when '+Convert(varchar(10),usersid )+''' then status else 0 end) as ‘status0 ‘ ,...............from temp
看一下交叉表的知识吧。
行列转换哈,1楼的办法就行吧。如果是SQL2005的话。