1

我想知道是否存在某种方式来选择下表...

ID | DOCNo | Date

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

在 SQL SERVER 2008 中做这样的事情:

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  

* DOCNo 表中的记录永远不会超过 3 条

我正在使用 SQL Server 2008。

谢谢!!!

4

2 回答 2

0

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) |
于 2013-10-23T01:02:10.893 回答
0

获得最终结果的一种简单方法是使用row_number()为每个生成序列docno,然后使用 CASE 表达式应用聚合函数:

select docno,
  max(case when seq = 1 then id end) id1,
  max(case when seq = 1 then date end) date1,
  max(case when seq = 2 then id end) id2,
  max(case when seq = 2 then date end) date2,
  max(case when seq = 3 then id end) id3,
  max(case when seq = 3 then date end) date3
from
(
  select id, docno, date,
    row_number() over(partition by docno order by date) seq
  from yourtable
) d
group by docno;

请参阅带有演示的 SQL Fiddle

于 2013-10-23T01:04:02.847 回答