数据查询

陌城灬流年閣 2013-01-22 06:34:47
表名:user
列名(用户名:userName(Nvarchar),月份:month(Int))
如图:
查询5月份的用户在6月,7月,8月,9月。出现的次数。
...全文
195 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
陌城灬流年閣 2013-01-23
  • 打赏
  • 举报
回复
叶子的方法易懂,fredrickhu的方法暂时还没懂,但是结果都一样。谢谢两位
陌城灬流年閣 2013-01-23
  • 打赏
  • 举报
回复
谢谢各位,出来了。感动了
--小F-- 2013-01-22
  • 打赏
  • 举报
回复
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
叶子 2013-01-22
  • 打赏
  • 举报
回复

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
*/
dengxinglian97966 2013-01-22
  • 打赏
  • 举报
回复
条件查询,。。。。

27,582

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧