Here is my query.
SELECT * FROM client_data where RefID =27
and Value
column's d开发者_Python百科atatype is nvarchar
.
TABLE is like below...
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 -
Expected RESULT:
Analysisid Reporting_Currency Reporting_Group Reporting_Language
44 EUR 0001 EN
44 EUR 0001 EN
44 USD 0002 DE
65 -
I tried with PIVOT
but couldn't succeed.
How can I do this?
Regards, Jn
First thing: There's a major problem with your data - as there's nothing to tie what you've defined as being separate rows together as such, other than the ordering of the result set. You should have a column in there called "item" that links these together.
That said I've imposed an ordering in the following SQL example:
;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
Returns:
AnalysisID Reporting_Currency Reporting_Group Reporting_Language
44 EUR 0001 EN
44 USD 0002 EN
44 EUR 0001 DE
65 NULL NULL NULL
精彩评论