这是我的查询。
SELECT * FROM client_data where RefID =27
和Value
列的数据类型为nvarchar
。
表格如下......
AnalysisID RefID RefColumn Value
44 27 Reporting_Currency EUR
44 27 Reporting_Currency EUR
44 27 Reporting_Currency USD
44 27 Reporting_Group 0001
44 27 Reporting_Group 0001
44 27 Reporting_Group 0002
44 27 Reporting_Language EN
44 27 Reporting_Language EN
44 27 Reporting_Language DE
65 27 Company_Code -
65 27 MANDT -
65 27 Reporting_Currency -
预期结果:
Analysisid Reporting_Currency Reporting_Group Reporting_Language
44 EUR 0001 EN
44 EUR 0001 EN
44 USD 0002 DE
65 -
我尝试使用PIVOT
,但无法成功。
我该怎么做?
此致 JN
答案 0 :(得分:1)
第一件事:您的数据存在一个主要问题 - 因为除了结果集的排序之外,没有任何内容可以将您定义为单独的行组合在一起。你应该有一个名为“item”的列将这些列链接在一起。
那就是说我在以下SQL示例中强加了一个排序:
;WITH CTE_TestData as (
select AnalysisID = 44, RefID=27, RefColumn = 'Reporting_Currency', Value='EUR'
union all select 44, 27, 'Reporting_Currency', 'EUR'
union all select 44, 27, 'Reporting_Currency', 'USD'
union all select 44, 27, 'Reporting_Group', '0001'
union all select 44, 27, 'Reporting_Group', '0001'
union all select 44, 27, 'Reporting_Group', '0002'
union all select 44, 27, 'Reporting_Language', 'EN'
union all select 44, 27, 'Reporting_Language', 'EN'
union all select 44, 27, 'Reporting_Language', 'DE'
union all select 65, 27, 'Company_Code', null
union all select 65, 27, 'MANDT', null
union all select 65, 27, 'Reporting_Currency', null
)
select AnalysisID, Reporting_Currency, Reporting_Group, Reporting_Language
from (
select *, rowno = row_number() OVER (PARTITION BY refid, analysisid, RefColumn Order By refid, analysisid, refcolumn)
from
CTE_TestData t
) unpvt
PIVOT (min(value) FOR RefColumn in ([Reporting_Currency], [Reporting_Group], [Reporting_Language])) pvt
返回:
AnalysisID Reporting_Currency Reporting_Group Reporting_Language
44 EUR 0001 EN
44 USD 0002 EN
44 EUR 0001 DE
65 NULL NULL NULL