如何根据结果数将SQL查询结果分组到多个列中?

时间:2016-02-19 12:16:34

标签: sql sql-server tsql reporting-services grouping

这是一个棘手的尝试和解释,但基本上我是在追随以下。

这些是我目前的结果:

Item  | Colours            | Sizes       | Prices
--------------------------------------------------
123   | Black,Blue,Green   | 32,34,36    |  9.99
123   | Black,Blue,Green   | 38,40,42    | 12.99
123   | Black,Blue,Green   | 44,46,48    | 15.99

我需要它显示如下:

Item | Colours          | Sizes    | Sizes1   | Size2    | Prices | Prices1 | Prices2
-----------------------------------------------------------------------------------
123  | Black,Blue,Green | 32,34,36 | 38,40,42 | 44,46,48 |  9.99  | 12.99   | 15.99

所以我需要根据行数动态创建列。

希望这是有道理的。

1 个答案:

答案 0 :(得分:0)

这是一种pivot查询。我更喜欢使用条件聚合:

select item, colours,
       max(case when seqnum = 1 then sizes end) as sizes_1,
       max(case when seqnum = 2 then sizes end) as sizes_2,
       max(case when seqnum = 3 then sizes end) as sizes_3,
       max(case when seqnum = 1 then prices end) as prices_1,
       max(case when seqnum = 2 then prices end) as prices_2,
       max(case when seqnum = 3 then prices end) as prices_3
from (select t.*,
             row_number() over (partition by item, colours order by prices) as seqnum
      from t
     ) t
group by item, colours;