sql统计

selg1984 2015-01-14 11:36:23
我按分组统计工作记录信息

比如说我工作记录中有
id userid content
1 2 333
2 3 444
3 4 555

其中2,3 属于1组 4 属于2组

分组表中有十个分组

我要显示十个分组的统计情况
分组 数量
1 2
2 1
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0

这个怎么写 谢谢
...全文
126 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
还在加载中灬 2015-01-14
  • 打赏
  • 举报
回复
userid 和 组 之间的关系,没有表,直接用说的吗~~
frankl123 2015-01-14
  • 打赏
  • 举报
回复
with tb1(id,userid,content) as
(
	select 1,2,333 union all
	select 2,3,444 union all
	select 3,4,555 union all
	select 4,5,555
),
tb2(userid,groupid) as--分组与userid对照表
(
	select 2,1 union all 
	select 3,1 union all 
	select 4,2 union all
	select 5,6
),
tb3(groupid) as--分组表
(
	select 1 union all 
	select 2 union all 
	select 4 union all 
	select 5 union all
	select 6 union all
	select 7 union all
	select 8 union all
	select 9 union all
	select 10 
)
select tb3.groupid 分组,count(tb1.id) 数量
from tb3
left join tb2 on tb3.groupid = tb2.groupid
left join tb1 on tb2.userid = tb1.userid
group by tb3.groupid

/*
分组          数量
----------- -----------
1           2
2           1
4           0
5           0
6           1
7           0
8           0
9           0
10          0
警告: 聚合或其他 SET 操作消除了 Null 值。

(9 行受影响)

*/
Ekun_sky 2015-01-14
  • 打赏
  • 举报
回复
with a(id,userid,content) as 
(select 1,2,333 union all
 select 2,3,444 union all
 select 3,4,555)
 select (case when userid=2 OR userid=3 then 1 when userid=4 then 2 else userid end)
   as c,COUNT(*) as d  from a 
 group by (case when userid=2 OR userid=3 then 1 when userid=4 then 2 else userid end)
selg1984 2015-01-14
  • 打赏
  • 举报
回复
引用 3 楼 ky_min 的回复:
userid 和 组 之间的关系,没有表,直接用说的吗~~
有表

27,579

社区成员

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

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