我努力解决我将在下面描述的问题,但仍未取得任何成功
所以,我有以下数据库结构: http://sqlfiddle.com/#!6/afb83b/1
我想要实现的不是显示相同的组3次(或在其他情况下多次显示),查询应该呈现以下输出而不是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
我尝试使用PIVOT,但是我在显示它时遇到了问题......
答案 0 :(得分:1)
你需要做这样的事情
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
动态版
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)