日期:2014-05-17  浏览次数:20464 次

数据查询
表名: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