我正在尝试将一些值转换为列,但我似乎无法将它们全部放在同一行中。我不确定是否有办法专门编写一个数据透视查询,或者我是如何尝试加入它们的。因为你可能比我自己知道更好,Stackoverflow,我会把我的可怕尝试留下来并尝试解释它......
select
[CARRIAGE_ID]
,[PUBLISH_FLAG]
,[COUNTER_PRESCRIBED]
,[ADT] AS 'ADT2008'
,[AWT] AS 'AWT2008'
,[AWE] AS 'AWE2008'
from [RISSxplr].[dbo].[ADT_MAP_FACT]
pivot (max([FIGURE]) FOR COUNT_TYPE IN ([ADT],[AWT],[AWE])) AS pCountType
WHERE [COUNT_YEAR] = 2008
给我一个像(样本)的结果:
CARRIAGE_ID PUBLISH_FLAG COUNTER_PRESCRIBED ADT2008 AWT2008 AWE2008
10041 1 P NULL NULL 36800
10041 1 P NULL 46400 NULL
10041 1 P 43000 NULL NULL
这些都共享相同的CARRIAGE_ID,我需要的是它们都在同一行,所以它看起来像这样:
CARRIAGE_ID PUBLISH_FLAG COUNTER_PRESCRIBED ADT2008 AWT2008 AWE2008
10041 1 P 43000 46400 36800
但我似乎无法实现这一点。请帮忙!并且一如既往地谢谢你。
编辑:我将从ADT_MAP_FACT
添加样本数据CARRIAGE_ID COUNT_TYPE COUNT_YEAR FIGURE NUMBER_DAYS PUBLISH_FLAG COUNTER_PRESCRIBED
10041 ADT 2008 43000 341 1 P
10041 ADT 2009 43400 292 1 P
10041 ADT 2010 44000 314 1 P
10041 ADT 2011 43300 341 1 P
10041 ADT 2012 42700 354 1 P
10041 AWE 2008 36800 95 1 P
10041 AWE 2009 36800 81 1 P
10041 AWE 2010 37900 87 1 P
10041 AWE 2011 37000 98 1 P
10041 AWE 2012 36500 98 1 P
10041 AWT 2008 46400 192 1 P
10041 AWT 2009 46900 162 1 P
10041 AWT 2010 47100 185 1 P
10041 AWT 2011 46900 189 1 P
10041 AWT 2012 46600 198 1 P
答案 0 :(得分:1)
作为分组依据,显示遇到的第一行,因此必须使用聚合函数(MAX / SUM)来获得所需的结果。
试试这个,
select
[CARRIAGE_ID]
,[PUBLISH_FLAG]
,[COUNTER_PRESCRIBED]
,sum([ADT]) AS 'ADT2008'
,sum([AWT]) AS 'AWT2008'
,sum([AWE]) AS 'AWE2008'
from [RISSxplr].[dbo].[ADT_MAP_FACT]
pivot (max([FIGURE]) FOR COUNT_TYPE IN ([ADT],[AWT],[AWE])) AS pCountType
WHERE [COUNT_YEAR] = 2008
group by [CARRIAGE_ID],
[PUBLISH_FLAG],
[COUNTER_PRESCRIBED];
在这里查看这个小提琴 - > fiddle link
答案 1 :(得分:1)
只需要聚合和GROUP BY
:
SELECT
[CARRIAGE_ID]
,[PUBLISH_FLAG]
,[COUNTER_PRESCRIBED]
,MAX([ADT]) AS 'ADT2008'
,MAX([AWT]) AS 'AWT2008'
,MAX([AWE]) AS 'AWE2008'
FROM [RISSxplr].[dbo].[ADT_MAP_FACT]
PIVOT (MAX([FIGURE]) FOR COUNT_TYPE IN ([ADT],[AWT],[AWE])) AS pCountType
WHERE [COUNT_YEAR] = 2008
GROUP BY [CARRIAGE_ID]
,[PUBLISH_FLAG]
,[COUNTER_PRESCRIBED]
演示:SQL Fiddle