我有表1.我希望输出如表2所示 请帮帮我
Table 1
Student_ID AttCode AttDate
101 AE 1-1-2011
101 H 1-2-2011
101 T 1-5-2011
101 H 1-7-2011
101 AU 1-8-2011
102 AE 1-1-2011
102 AE 1-3-2011
102 H 1-4-2011
102 V 1-5-2011
Table 2
Student_ID FromDate To date ConsecutiveAbs AttCodes
101 1-1-2011 1-2-2011 2 AE,H
101 1-5-2011 1-8-2011 4 T,AE,H,AU
102 1-1-2011 1-1-2011 1 AE
102 1-3-2011 1-5-2011 2 AE,H,V
答案 0 :(得分:0)
你走了!完整的脚本,只需确保对每种可能的情况都进行测试,如果符合您的需要,请不要忘记将其标记为答案:
IF OBJECT_ID('TEST1') IS NOT NULL
DROP TABLE TEST1
GO
CREATE TABLE TEST1
(
STUDENTID INT ,
ATTCODE VARCHAR(2) ,
ATTDATE DATE
)
GO
INSERT INTO TEST1
VALUES
('101','AE','20110101'),
('101','H','20110102'),
('101','T','20110105'),
('101','H','20110107'),
('101','AU','20110108'),
('102','AE','20110101'),
('102','AE','20110103'),
('102','H','20110104'),
('102','V','20110105')
GO
IF OBJECT_ID('TEST2') IS NOT NULL
DROP TABLE TEST2
GO
CREATE TABLE TEST2
(
STUDENTID INT,
FROMDATE DATE,
TODATE DATE,
CONSECUTIVEABS INT,
ATTCODES VARCHAR(255)
)
GO
INSERT INTO TEST2
SELECT TEST1.STUDENTID,TEST1.ATTDATE,TEST1.ATTDATE,1,TEST1.ATTCODE
FROM TEST1
JOIN
(
SELECT STUDENTID,MIN(ATTDATE) ATTDATE
FROM TEST1
GROUP BY STUDENTID
) MI ON MI.STUDENTID=TEST1.STUDENTID AND MI.ATTDATE=TEST1.ATTDATE
DECLARE @STUDENTID INT, @ATTCODE VARCHAR(2), @ATTDATE DATE
DECLARE CRS CURSOR LOCAL FAST_FORWARD FOR
SELECT TEST1.STUDENTID,TEST1.ATTCODE,TEST1.ATTDATE
FROM TEST1
LEFT JOIN TEST2 ON TEST1.STUDENTID=TEST2.STUDENTID AND TEST1.ATTCODE=TEST2.ATTCODES AND TEST1.ATTDATE=TEST2.FROMDATE
WHERE TEST2.STUDENTID IS NULL
ORDER BY 1,3 ASC
OPEN CRS
FETCH NEXT FROM CRS INTO @STUDENTID, @ATTCODE, @ATTDATE
WHILE @@FETCH_STATUS=0
BEGIN
IF EXISTS
(
SELECT 1
FROM TEST2
WHERE STUDENTID=@STUDENTID AND DATEADD(DD,1,TODATE)=@ATTDATE
)
UPDATE TEST2
SET TODATE=@ATTDATE, ATTCODES+=','+@ATTCODE, CONSECUTIVEABS+=1
WHERE STUDENTID=@STUDENTID AND DATEADD(DD,1,TODATE)=@ATTDATE
ELSE
INSERT INTO TEST2
SELECT @STUDENTID,@ATTDATE,@ATTDATE,1,@ATTCODE
FETCH NEXT FROM CRS INTO @STUDENTID, @ATTCODE, @ATTDATE
END
SELECT * FROM TEST2
ORDER BY 1,2
它没有处理的一种情况是你在输入表中有相同的studenId和attdate以及不同的attcode。你没有提到任何关于这种情况的事情,这就是为什么它不是由上面的代码处理的。