如何安排以下结果集
meal_type menu_item_id
2 111
2 222
2 333
2 444
2 555
3 666
3 777
3 888
3 999
到
2 3
111 666
222 777
333 888
444 999
555
使用pivot或unpivot
答案 0 :(得分:2)
您的数据存在问题 - 没有组来源,PIVOT假设聚合函数 如果数据很小(主题为:-)),则可以使用ROW_NUMBER()函数创建分组字段。我假设源表名是" test"
with ordered as (
select
row_number() OVER (PARTITION by meal_type order by menu_item_id) num,
* from [test]
)
select
max(case [meal_type] when 2 then [menu_item_id] end) as [2],
max(case [meal_type] when 3 then [menu_item_id] end) as [3]
from ordered group by num
答案 1 :(得分:0)
您可以使用ROW_NUMBER和PIVOT:
来获得结果 SELECT [2] ,
[3]
FROM ( SELECT * ,
ROW_NUMBER() OVER ( PARTITION BY meal_type ORDER BY menu_item_id ) R
FROM dbo.Meal
) s PIVOT( MAX(menu_item_id) FOR meal_type IN ( [2], [3] ) ) pvt;