日期:2014-05-17 浏览次数:20582 次
----------------------------
-- 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
----------------结果------