試試這個:
SET NOCOUNT ON
DECLARE @T1 TABLE (FLAG CHAR(10),DATE CHAR(20),ID INT IDENTITY(1,1))
INSERT INTO @T1 VALUES ('N','01/01/2017');
INSERT INTO @T1 VALUES ('N','03/01/2017');
INSERT INTO @T1 VALUES ('N','04/01/2017');
INSERT INTO @T1 VALUES ('Y','06/01/2017');
INSERT INTO @T1 VALUES ('Y','09/01/2017');
INSERT INTO @T1 VALUES ('N','12/01/2017');
INSERT INTO @T1 VALUES ('N','14/01/2017');
INSERT INTO @T1 VALUES ('Y','15/01/2017');
INSERT INTO @T1 VALUES ('Y','16/01/2017');
INSERT INTO @T1 VALUES ('Y','19/01/2017');
INSERT INTO @T1 VALUES ('N','23/01/2017');
DECLARE @T2 TABLE (FLAG CHAR(10),DATE CHAR(20),ID INT IDENTITY(1,1))
DECLARE @T3 TABLE (FLAG CHAR(10),DATE CHAR(20),ID INT IDENTITY(1,1))
DECLARE @FLAG CHAR(10),@ID INT,@OLD CHAR(10)
SET @OLD=(SELECT FLAG FROM @T1 WHERE ID=1)
DECLARE C CURSOR FOR
SELECT FLAG,ID FROM @T1 WHERE ID>1
OPEN C
FETCH NEXT FROM C INTO @FLAG,@ID
WHILE @@FETCH_STATUS=0
BEGIN
IF(@OLD<>@FLAG)
BEGIN
IF @FLAG='Y'
INSERT INTO @T2 SELECT FLAG,DATE FROM @T1 WHERE [email protected]
ELSE
INSERT INTO @T3 SELECT FLAG,DATE FROM @T1 WHERE [email protected]
END
SET @[email protected]
FETCH NEXT FROM C INTO @FLAG,@ID
END
CLOSE C
DEALLOCATE C
SELECT A.FLAG,A.DATE,B.FLAG,B.DATE FROM @T2 A INNER JOIN @T3 B
ON A.ID=B.ID
請寫下評論,至少你爲什麼downvoted! – Bob
什麼是實際要求。我無法理解?你想要Y和N在不同的列或其他東西? –
這樣的東西可能是你要找的東西:'SELECT Flag1 ='Y',Date1 = MIN(T. [Date]),Flag2 ='N',Date2 = C. [Date] FROM myTable T CROSS APPLY (SELECT Date([Date])FROM myTable WHERE Flag ='N'AND [Date]> = T. [Date])C([Date])WHERE T.Flag ='Y'GROUP BY C. [Date]; ' – ZLK