合并第1行和第2行,第3行和第4行,依此类推

时间:2017-01-18 17:08:50

标签: sql sql-server-2005

假设我有行表,

Id  Value
----------
1    a
1    b
1    c
1    d
1    e
1    f

,预期结果应为,

Id  Value1   Value2
-------------------
1    a        b
1    c        d
1    e        f

我在这里很困惑。

3 个答案:

答案 0 :(得分:4)

好的,这绝对是一种更简单的方法,但这样做有效:

WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Value)
    FROM dbo.YourTable
)
SELECT  Id,
        MIN(CASE WHEN RN % 2 = 1 THEN Value END) Value1, 
        MIN(CASE WHEN RN % 2 = 0 THEN Value END) Value2
FROM CTE
GROUP BY Id,
         RN - ((RN - 1) % 2);

结果如下:

╔════╦════════╦════════╗
║ Id ║ Value1 ║ Value2 ║
╠════╬════════╬════════╣
║  1 ║ a      ║ b      ║
║  1 ║ c      ║ d      ║
║  1 ║ e      ║ f      ║
╚════╩════════╩════════╝

答案 1 :(得分:1)

;WITH cte AS
(
  SELECT *, ROW_NUMBER() OVER (ORDER BY value) AS RowNum
  FROM YourTable
)

SELECT 
    c1.id
  , c1.value as Value1
  , c2.value as Value2
FROM cte c1
LEFT JOIN cte c2 ON c1.rownum = c2.rownum - 1
WHERE c1.RowNum % 2 = 1

答案 2 :(得分:0)

select      Id
           ,min(Value)  as Value1
           ,max(Value)  as Value2

from       (select      Id,Value
                       ,(row_number () over 
                            (partition by Id order by Value)+1)/2 as group_id

            from        mytable as t
            ) t

group by    Id      
           ,group_id