本文介紹了來自一個透視表的 SQL FOR XML 多級的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我一直在嘗試使用 FOR XML 來執行以下操作,但沒有成功.
I've been trying to use FOR XML without success to do the following.
源表:
Country | ID | 1950 | 1955
-----------------------------------------------------
Country 1 | 1 | 2.43 | 2.55
Country 2 | 2 | 4.54 | 42.15
所需的輸出:
<locations>
<location>
<loc name='Country 1' id='1' />
<dub>
<data year='1950' value='2.43' />
<data year='1955' value='2.55' />
</dub>
</location>
<location>
<loc name='Country 2' id='2' />
<dub>
<data year='1950' value='4.54' />
<data year='1955' value='42.15' />
</dub>
</location>
</locations>
是否有必要為配音元素取消旋轉?我想要最簡單的 SQL 查詢.我認為 FOR XML 太難用了.您應該能夠僅在列名上使用簡單的 XPath 來指定層次結構,但它不會接受,例如,[dub/data/@year=1955/@value]
作為列名的名稱列 [1950]
.
Will it be necessary to unpivot for the dub element? I wanted the simplest SQL query possible.
I think FOR XML is too difficult to use. You should be able to specify the hierarchy just using simple XPath on column names but it won't accept, for example, [dub/data/@year=1955/@value]
as the name of the column [1950]
.
推薦答案
SQL Fiddle
MS SQL Server 2012 架構設置:
create table YourTable
(
Country varchar(20),
ID int,
[1950] numeric(5,2),
[1955] numeric(5,2)
)
insert into YourTable values
('Country 1', 1, 2.43, 2.55),
('Country 2', 2, 4.54, 42.15)
查詢 1:
select T.Country as 'loc/@name',
T.ID as 'loc/@id',
(
select 1950 as 'data/@year',
T.[1950] as 'data/@value',
null,
1955 as 'data/@year',
T.[1955] as 'data/@value'
for xml path(''), type
) as dub
from YourTable as T
for xml path('location'), root('locations'), type
結果:
<locations>
<location>
<loc name="Country 1" id="1" />
<dub>
<data year="1950" value="2.43" />
<data year="1955" value="2.55" />
</dub>
</location>
<location>
<loc name="Country 2" id="2" />
<dub>
<data year="1950" value="4.54" />
<data year="1955" value="42.15" />
</dub>
</location>
</locations>
這篇關于來自一個透視表的 SQL FOR XML 多級的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!