Skip to content
Advertisement

Pivot table in SQL Server 2016

I am having problem with pivoting a table in SQL Server 2016. Consider the following data/query

I’m trying to pivot on dt and mn for the values in fc. So basically I am looking for this output.

I was trying to add to max function like this but it doesn’t work

Can someone please help modify my query to produce the output above?

Advertisement

Answer

One option uses row_number() and conditional aggregation. Assuming that you want the latest date in the first column:

If you want to handle more than 2 rows per group, then you need to expand the select clause with more conditional expressions.

Demo on DB Fiddle:

cid | cname | fc1_dt     | fc1_name |  fc1_mn | fc2_dt     | fc2_name | fc2_mn
--: | :---- | :--------- | :------- | ------: | :--------- | :------- | -----:
123 | test  | 2020-03-17 | BELLE    | 3782703 | 2020-03-12 | WOO      |  25679
345 | test2 | 2019-03-17 | king     | 3782703 | 2019-03-12 | east     |  25679
111 | test3 | 2019-02-12 | east     |       2 | null       | null     |   null
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement