日期:2014-05-17 浏览次数:20725 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-11 14:28:07
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] varchar(4),[name] varchar(4),[versions] varchar(1),[beginvalue] int,[endvalue] int)
insert [huang]
select 'ABCD','铭牌','B',10101,19999 union all
select 'ABCD','铭牌','B',10001,10002 union all
select 'ABCD','铭牌','A',10101,19999 union all
select 'ABCD','铭牌','A',10001,10002 union all
select 'ABCD','铭牌','A',10005,10005
--------------开始查询--------------------------
;WITH ym AS (
select TOP 100 PERCENT Id,name,[versions],CASE WHEN CAST([beginvalue] AS VARCHAR)=CAST([endvalue] AS VARCHAR) THEN CAST([beginvalue] AS VARCHAR) ELSE CAST([beginvalue] AS VARCHAR)+'-'+CAST([endvalue] AS VARCHAR) END [区间]
from [huang]
ORDER BY [versions] DESC,[beginvalue])
select a.id,a.name,a.versions,
stuff((select ','+[区间] from ym b
where b.id=a.id and b.name=a.name and b.[versions]=a.[versions]
ORDER BY [区间]
for xml path('')),1,1,'') '区间'
from ym a
group by a.id,a.name,a.versions
ORDER BY a.versions DESC
----------------结果----------------------------
/*
id name versions 区间
---- ---- -------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ABCD 铭牌 B 10001-10002,10101-19999
ABCD 铭牌 &nbs