从具有相同ID的不同行中移动数据,这些行位于sql的相同行但不同的列中

时间:2015-08-06 20:50:11

标签: sql sql-server rownum

我有像

这样的数据
  ID   ded1   ded2   ded3   ded4 
  ------------------------------
  1    2
  1    3
  1    4 

我想:

ID   ded1   ded2   ded3   ded4
------------------------------
1    2      3      4

ded4为空,因为有3个值,如果有第4个值则ded4填满

2 个答案:

答案 0 :(得分:2)

当且仅当您的列数有限而且您觉得自己不需要将值分配给动态命名列的函数时,您可以执行此操作以下方式:

使用像row_number()这样的分析函数来确定顺序 - 哪个值应该在哪个列下,然后将结果分组为id并取max()值以使其中的一行你的CASE陈述。

SELECT
  id,
  MAX(CASE WHEN ded_rn = 1 THEN ded1 END) AS ded1,
  MAX(CASE WHEN ded_rn = 2 THEN ded1 END) AS ded2,
  MAX(CASE WHEN ded_rn = 3 THEN ded1 END) AS ded3,
  MAX(CASE WHEN ded_rn = 4 THEN ded1 END) AS ded4
FROM(
  SELECT
    *,
    row_number() OVER (PARTITION BY id ORDER BY ded1) AS ded_rn
  FROM 
    tbl
   ) foo
GROUP BY id

这是一个SQL fiddle,提供了带有样本数据的讨论案例。

答案 1 :(得分:1)

虽然@ConsiderMe的回答非常正确,但如果您对该组有问题,或者您希望从源表中包含其他列,则还可以执行4次联接。这有时是唯一可行的解​​决方案。 (顺便说一句它与这段代码基本相同)。

此代码比@ CondiderMe的答案稍慢,因为它需要3次扫描/搜索,而他只有2次。所以如果需要,只能使用它。

With addRN AS
(
  SELECT *,
        row_number() OVER (PARTITION BY id ORDER BY ded1) AS rn
  FROM tbl
)
SELECT ids.id, r1.ded1 as ded1, r2.ded1 as ded2, r3.ded1 ad ded3, r4.ded1 as ded4
FROM (SELECT DISTINCT id FROM tbl) ids
LEFT JOIN addRN r1 ON ids.id = r1.id AND rn = 1
LEFT JOIN addRN r2 ON ids.id = r2.id AND rn = 2
LEFT JOIN addRN r3 ON ids.id = r3.id AND rn = 3
LEFT JOIN addRN r3 ON ids.id = r3.id AND rn = 4