SQL-将多行转换为多列

时间:2018-10-30 02:58:42

标签: sql sql-server

这里需要简单的帮助。经过了各种解决方案,例如用例和行号,数据透视,但找不到合适的解决方案。

基本上,我想使用该组的Name值并找到所有非null和不同的值,并将结果显示在一行中。

输入

Name | Color
John | Blue
John | Green
Mary | NULL
Mary | Yellow
Mary | Pink
Mary | Pink

预期产量

Name | Color1 | Color2 | Color3
John | Blue   | Green  |  NULL
Mary | Yellow | Pink   |  NULL

目前,我来到了下面的查询,但看起来与我想要的结果相去甚远。感谢您的协助,谢谢!

select  Name,
    max(case when seqnum = 1 then Color end) as Color1,
    max(case when seqnum = 2 then Color end) as Color2,
    max(case when seqnum = 3 then Color end) as Color3
from (select table.*, row_number() over (partition by Name order by Name) as seqnum
    from table
    ) table
group by Name

2 个答案:

答案 0 :(得分:2)

我认为您应该在这里使用Function Nombrespositifs( x as range) End function ,而不是DENSE_RANK

ROW_NUMBER

enter image description here

Demo

尚不清楚您实际上要对颜色使用什么顺序,因为在您的预期输出中,约翰的颜色在递增,而玛丽的颜色在递减。我选择升序排列,最后SELECT Name, MAX(CASE WHEN rnk = 1 THEN Color END) AS Color1, MAX(CASE WHEN rnk = 2 THEN Color END) AS Color2, MAX(CASE WHEN rnk = 3 THEN Color END) AS Color3 FROM ( SELECT *, DENSE_RANK() OVER (PARTITION BY Name ORDER BY CASE WHEN Color IS NOT NULL THEN 0 ELSE 1 END, Color) rnk FROM yourTable ) t GROUP BY Name; 个。

答案 1 :(得分:0)

您可以像示例中那样以json格式获取结果:

SELECT concat(
    '{',
    name,
    ':[',
    GROUP_CONCAT(color),
    ']}'
) FROM `test` GROUP BY name

结果:

{
  John: [Blue, Green]
}
{
  Mary: [NULL, Yellow, Pink, Pink]
}

Demo