0

I struggled to solve the issue I will describe bellow, but still without any success

So, I have the following database structure: http://sqlfiddle.com/#!6/afb83b/1

What I want to achieve is instead of displaying the same group 3 times (or in other cases multiple times), the query should render the following output instead of the output from SQLFiddle:

id_project  | id_group  | A  | R  | K  |  Year  | Month  | Value
1             1           A1   R1   K1    2017    05       0.77
1             2           A1   R1   K2    2017    05       0.3
1             3           A1   R1   K3    2017    05       0.22
1             4           A1   R1   K4    2017    05       0.45
...
1             100         A3   R3   K8    2017    05       0.34 

I tried using PIVOT, but I have issues on displaying it like I want it..

rosuandreimihai
  • 656
  • 3
  • 16
  • 39

1 Answers1

1

You need to do something like this

select * from
(
select dd.id_project, dd.id_group,dmn.map, dd.year, dt.type,dd.month, dd.value from dm_data dd
left join dm_group_map dgm ON dgm.id_group = dd.id_group 
left join dm_mapping dm ON dm.id_map = dgm.id_map
left join dm_map_names dmn ON dmn.id_map_name = dm.id_map_name
left join dm_type dt ON dt.id_type = dm.id_type
) a
pivot (max(map) for type in ([A],[R],[K]))pv

Dynamic version

declare @sql varchar(max)='',@col_list varchar(max)=''

set @col_list =stuff((select  distinct ','+quotename(type) from dm_type for xml path('')),1,1,'')

set @sql = '
select * from
(
select dd.id_project, dd.id_group,dmn.map, dd.year, dt.type,dd.month, dd.value from dm_data dd
left join dm_group_map dgm ON dgm.id_group = dd.id_group 
left join dm_mapping dm ON dm.id_map = dgm.id_map
left join dm_map_names dmn ON dmn.id_map_name = dm.id_map_name
left join dm_type dt ON dt.id_type = dm.id_type
) a
pivot (max(map) for type in ('+@col_list+'))pv'

exec (@sql)  
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172