SQL Server 能这样分组吗
SQL Server 2008 R2
CREATE TABLE Test
(
ID INT IDENTITY(1, 1) PRIMARY KEY,
ItemCode VARCHAR(100) NOT NULL,
ItemProperty VARCHAR(100) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL
)
INSERT Test VALUES('A100', 'D800', '2010-1-1', '2010-3-31')
INSERT Test VALUES('A100', 'D800', '2010-4-1', '2010-6-30')
INSERT Test VALUES('A100', 'D800', '2010-7-1', '2010-9-30')
INSERT Test VALUES('A100', 'D800', '2010-10-1', '2010-12-31')
INSERT Test VALUES('A100', 'D800', '2011-2-1', '2011-12-31')
INSERT Test VALUES('A100', 'X05', '2012-1-1', '2012-12-31')
INSERT Test VALUES('A100', 'D800', '2013-1-1', '2013-5-31')
INSERT Test VALUES('A100', 'D800', '2013-6-1', '2013-12-31')
INSERT Test VALUES('A200', 'F9', '2010-1-1', '2013-12-31')
希望使用一条select语句查询ItemCode为“A100”的数据,查出如下的结果
ItemCode ItemProperty StartDate EndDate
A100 D800 2010-1-1 2010-12-31
A100 D800 2011-2-1 2011-12-31
A100 X05 2012-1-1 2012-12-31
A100 D800 2013-1-1 2013-12-31
PS 2010-12-31到2011-1-31为断链部分。所以要查出来前两条的结果。
------解决方案--------------------;WITH TT
AS(
SELECT * FROM test WHERE itemcode = 'A100'),
T1 AS(
SELECT id ,itemproperty,
startdate ,itemcode,
( SELECT min(enddate)
FROM TT AS B
WHERE B.id >= A.id
AND NOT EXISTS ( SELECT *
FROM TT AS c
WHERE b.id = c.id-1 AND DATEADD(dd,-1,c.startdate)=b.enddate AND b.itemproperty = c.itemproperty)
) AS enddate
FROM TT AS A),
T2 AS(
SELECT ROW_NUMBER() OVER(PARTITION BY itemproperty,enddate ORDER BY id) AS num,* FROM T1)
SELECT itemcode,itempropert