How can I arrange the following result set
meal_type menu_item_id
2 111
2 222
2 333
2 444
2 555
3 666
3 777
3 888
3 999
to
2 3
111 666
222 777
333 888
444 999
555
using pivot or unpivot
The problem with your data - no source for group, PIVOT assumes aggregate function If you data are small (it is subject for separate topic :-) ), you can create grouping field, using ROW_NUMBER() function. I assume source table name is "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
You can achieve the result using ROW_NUMBER and 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.