sql语句,显示数据集
table1表
编号 内容 序号
1 aa 1
4 bb 2
5 cc 3
8 aa 4
10 dd 5
13 dd 6
17 sdf 7
19 df 8
20 sdf 9
要出来这样的数据
编号 个数 序号
1-4 2个 1,2
4-10 3个 3,4,5
13-20 4个 6,7,8,9
[解决办法]
----------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2013-09-17 16:05:33
-- Verstion:
-- Microsoft SQL Server 2012 - 11.0.2100.60 (X64)
--Feb 10 2012 19:39:15
--Copyright (c) Microsoft Corporation
--Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([编号] int,[内容] varchar(3),[序号] int)
insert [tb]
select 1,'aa',1 union all
select 4,'bb',2 union all
select 5,'cc',3 union all
select 8,'aa',4 union all
select 10,'dd',5 union all
select 13,'dd',6 union all
select 17,'sdf',7 union all
select 19,'df',8 union all
select 20,'sdf',9
--------------开始查询--------------------------
SELECT
'1-4' AS 编号,SUM(CASE WHEN 编号 BETWEEN 1 AND 4 THEN 1 ELSE 0 END ) AS 个数,
stuff((select ','+LTRIM([序号]) from tb t where 编号 BETWEEN 1 AND 4 for xml path('')), 1, 1, '')
FROM
TB t
UNION ALL
SELECT
'4-10' AS 编号,SUM(CASE WHEN 编号 BETWEEN 5 AND 10 THEN 1 ELSE 0 END ) AS 个数,
stuff((select ','+LTRIM([序号]) from tb t where 编号 BETWEEN 5 AND 10 for xml path('')), 1, 1, '')
FROM
TB t
UNION ALL
SELECT
'13-20' AS 编号,SUM(CASE WHEN 编号 BETWEEN 13 AND 20 THEN 1 ELSE 0 END ) AS 个数,
stuff((select ','+LTRIM([序号]) from tb t where 编号 BETWEEN 13 AND 20 for xml path('')), 1, 1, '')
FROM
TB t
----------------结果----------------------------
/* 编号 个数
----- ----------- ----------------------------------------------------------------------------------------------------------------
1-4 2 1,2
4-10 3 3,4,5
13-20 4 6,7,8,9
(3 行受影响)
*/