如何取出group by的子集

a550759049 2011-03-20 10:59:50
表dt
id tag
1 1
2 1
3 2
4 3
5 2
6 1


select tag, count(*)num from dt group by tag


tag num 我还想取出所含id,怎么修改?
1 3 1,2,6
2 2 3,5
3 1 4
...全文
135 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
喜-喜 2011-03-20
  • 打赏
  • 举报
回复
use test
go
if object_id('test.dbo.tb') is not null drop table tb
-- 创建数据表
create table tb
(
id int,
tag int
)
go
--插入测试数据
insert into tb select 1,1
union all select 2,1
union all select 3,2
union all select 4,3
union all select 5,2
union all select 6,1
go
--代码实现

if object_id('test.dbo.f_str') is not null drop function f_str
go
create function dbo.f_str(@tag varchar(10)) returns varchar(1000)
as
begin
declare @str varchar(1000)
select @str = isnull(@str + ',' , '') + rtrim(id) from tb where tag = @tag
return @str
end
go
--调用函数
select distinct tag,num=count(*),id=dbo.f_str(tag)
from tb
group by tag

/*测试结果

tag num id
---------------------
1 3 1,2,6
2 2 3,5
3 1 4

(3 行受影响)
*/
--小F-- 2011-03-20
  • 打赏
  • 举报
回复
select
*
from
(select tag, num=count(*) from #temp group by tag) a
join
(select tag,id=stuff((select ',' + CAST(id as varchar(10)) from #temp where tag = a.tag for xml path('')), 1, 1, '')) b
on
a.tag=b.tag
Shawn 2011-03-20
  • 打赏
  • 举报
回复
create table #temp
(
id int,
tag int
)
insert #temp
select 1, 1union all
select 2, 1union all
select 3, 2union all
select 4, 3union all
select 5, 2union all
select 6, 1
go
--SQL:
select * from
(select tag, num=count(*) from #temp group by tag) a
cross apply
(select id=stuff((select ',' + CAST(id as varchar(10)) from #temp where tag = a.tag for xml path('')), 1, 1, '')) b
/*
tag num id
1 3 1,2,6
2 2 3,5
3 1 4
*/

27,579

社区成员

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

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