SQL将行数据分组为一行

时间:2018-08-19 21:18:46

标签: sql sql-server dense-rank

我在这样的表中有数据:

enter image description here

我要整理表格数据,以便每行最多可以得到3个字母(按帐号分组)。

以下是我想要的结果:

enter image description here

我可以使用密集排名对帐号进行分组,但是不确定如何以上述格式获取我想要的数据。

enter image description here

逻辑: 帐户123有4个字母。最终结果按帐号(前3个字母)分组,因为每行最多只能有3个字母。第四个字母必须在第二行。

2 个答案:

答案 0 :(得分:3)

这里有一个使用conditional aggregation的选项,首先创建一个row_number,然后使用%(模运算符)每3行创建一个行分组:

select account_number, 
       max(case when rn % 3 = 1 then letter end) as letter1,
       max(case when rn % 3 = 2 then letter end) as letter2,
       max(case when rn % 3 = 0 then letter end) as letter3
from (
    select *, row_number() over (partition by account_number, rn % 3 order by rn) newrn
    from (
       select *, row_number() over (partition by account_number order by letter) rn
        from yourtable 
        ) t
    ) y
group by account_number, newrn
order by account_number

答案 1 :(得分:0)

我只需要打一次row_number()

select account_number,
       max(case when seqnum % 3 = 1 then letter end) as letter_a,
       max(case when seqnum % 3 = 2 then letter end) as letter_b,
       max(case when seqnum % 3 = 0 then letter end) as letter_c
from (select t.*,
             row_number() over (partition by account_number order by letter) as seqnum
      from t
     ) t
group by account_number, floor( (seqnum - 1) / 3)
order by account_number, min(seqnum);