SQL小提琴
MS SQL Server 2008 架构设置:
CREATE TABLE Table1
([ID] int, [DOCNo] int, [Date] varchar(9))
;
INSERT INTO Table1
([ID], [DOCNo], [Date])
VALUES
(1, 20, '12-DEC-12'),
(2, 21, '02-NOV-12'),
(3, 20, '18-JAN-13'),
(4, 20, '10-APR-13'),
(5, 22, '12-DEC-12'),
(6, 23, '21-JAN-13'),
(7, 23, '24-FEB-13')
;
查询 1:
SELECT r1.DOCNo,
r1.ID as ID1, r1.Date as Date1,
r2.ID as ID2, r2.Date as Date2,
r3.ID as ID3, r3.Date as Date3
FROM Table1 r1
LEFT OUTER JOIN Table1 r2 ON r1.DOCNo = r2.DOCNo AND r1.ID < r2.ID
LEFT OUTER JOIN Table1 r3 ON r1.DOCNo = r3.DOCNo AND r1.ID < r3.ID
AND r2.ID < r3.ID
WHERE r1.ID = (SELECT min(ID)
FROM Table1
WHERE DOCNo = r1.DOCNo
GROUP BY DOCNo)
AND (CASE WHEN (SELECT count(*)
FROM Table1
WHERE DOCNo = r1.DOCNo
GROUP BY DOCNo) = 2 THEN r2.ID
WHEN (SELECT count(*)
FROM Table1
WHERE DOCNo = r1.DOCNo
GROUP BY DOCNo) = 3 THEN r3.ID ELSE 1 END) IS NOT NULL
结果:
| DOCNO | ID1 | DATE1 | ID2 | DATE2 | ID3 | DATE3 |
|-------|-----|-----------|--------|-----------|--------|-----------|
| 20 | 1 | 12-DEC-12 | 3 | 18-JAN-13 | 4 | 10-APR-13 |
| 21 | 2 | 02-NOV-12 | (null) | (null) | (null) | (null) |
| 22 | 5 | 12-DEC-12 | (null) | (null) | (null) | (null) |
| 23 | 6 | 21-JAN-13 | 7 | 24-FEB-13 | (null) | (null) |