选择行作为同一个表的列

时间:2015-07-31 18:57:13

标签: sql sql-server sql-server-2012

我有一张像这样的表:

id name   date
---------------------
1  Ann    01/10/2015
2  Betty  01/31/2015
3  Charly 02/15/2015
4  David  03/30/2015
5  Ernest 04/04/2015
6  Frank  04/16/2015
7  Gale   05/02/2015
8  Jack   05/09/2015
9  Kelly  07/31/2015

如何一次检索3行:

1  Ann    01/10/2015 2  Betty  01/31/2015 3  Charly 02/15/2015
4  David  03/30/2015 5  Ernest 04/04/2015 6  Frank  04/16/2015
7  Gale   05/02/2015 8  Jack   05/09/2015 9  Kelly  07/31/2015

所以我从Id 1,4和7开始有3行

我使用SQL Server 2012

1 个答案:

答案 0 :(得分:0)

Should you do this in SQL? Nope, I agree with the comment.
Can it be done in SQL? Certainly.

;with cte AS (SELECT *,(ROW_NUMBER() OVER(ORDER BY id)-1)/3 AS Rnk                     
              FROM Table1)
     ,cte2 AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY Rnk ORDER BY id) AS RN
               FROM cte)
SELECT a.*,b.id AS id2, b.name AS name2, b.date AS date2
          ,c.id AS id3, c.name AS name3, c.date AS date3
FROM cte2 a
LEFT JOIN cte2 b
  ON a.Rnk = b.Rnk
  AND a.RN = b.RN - 1
LEFT JOIN cte2 c
  ON a.Rnk = c.Rnk
  AND a.RN = c.RN - 2
WHERE a.RN = 1  
 ; 

Demo: SQL Fiddle

Using integer division with a ROW_NUMBER() you get a value that repeats for 3 rows that can be used to slice them up.

Edit: LEFT JOIN so as to not exclude incomplete rows.