读书人

数据查询,该怎么处理

发布时间: 2013-01-26 13:47:03 作者: rapoo

数据查询
表名:user
列名(用户名:userName(Nvarchar),月份:month(Int))
如图:数据查询,该怎么处理
查询5月份的用户在6月,7月,8月,9月。出现的次数。
sql
[解决办法]


declare @user table([userName] varchar(6),[month] int)
insert @user
select '张三',5 union all
select '李四',5 union all
select '王五',5 union all
select '赵柳',6 union all
select '王麻子',6 union all
select '张三',6 union all
select '李四',6 union all
select '张三',6 union all
select '李四',7 union all
select '李四',7 union all
select '李四',7 union all
select '王五',7 union all
select '王五',8 union all
select '王五',8 union all
select '王五',8 union all
select '赵柳',9 union all
select '赵柳',9 union all
select '赵柳',9

select username,
(select count(1) from @user where username=t.username and [month]=6) as [6月],
(select count(1) from @user where username=t.username and [month]=7) as [7月],
(select count(1) from @user where username=t.username and [month]=8) as [8月],
(select count(1) from @user where username=t.username and [month]=9) as [9月]
from @user t where [month]=5

/*
username 6月 7月 8月 9月
-------- ----------- ----------- ----------- -----------
张三 2 0 0 0
李四 1 3 0 0
王五 0 1 3 0
*/

[解决办法]
select
username,
sum(case when [month]=6 then 1 else 0 end) as [6月],
sum(case when [month]=7 then 1 else 0 end) as [7月],
sum(case when [month]=8 then 1 else 0 end) as [8月],
sum(case when [month]=9 then 1 else 0 end) as [9月]
from
tb
where
userName in(select userName from tb where [month]=5)
group by
username

读书人网 >SQL Server

热点推荐