我有XML列,如下所示
<XMLDoc>
<AAA>
<Name>Name_A</Name>
<Value>Val_A</Value>
<dateReported>1/1/2001<dateReported>
</AAA>
<AAA>
<Name>Name_B</Name>
<Value>Val_B</Value>
<dateReported>1/1/2014<dateReported>
</AAA>
<AAA>
<Name>Name_C</Name>
<Value>Val_C</Value>
<dateReported>1/1/2012<dateReported>
</AAA>
<AAA>
<Name>Name_D</Name>
<Value>Val_D</Value>
<dateReported>1/1/2011<dateReported>
</AAA></x>
<BB><ID>12</ID><BB>
<CC><Type>XML</Type></CC>
</XMLDoc>
我需要获取最大dateReported的名称和值节点。到目前为止,我的sQL如下所示
SELECT
Col1 = Col.value('(/XMLDoc/x/AAA/Name)[1]', 'varchar(255)'),
Col2 = Col.value('(/XMLDoc/x/AAA/Value)[2]', 'varchar(255)'),
Col3 = Col.value('(/XMLDoc/BB/ID)[1]', 'varchar(255)'),
Col4 = Col.value('(/XMLDoc/CC/Type)[1]', 'varchar(255)')
FROM
table t
基本上我需要输出为Name_B
,Val_B
,12
,XML
,因为AAA的datereported
具有最大值。
答案 0 :(得分:0)
你可以尝试这样的事情 - 设置一个CTE(公用表表达式)来提取&#34;提取&#34;将XML值转换为关系格式,然后对该结果集执行简单的SELECT
:
;WITH XmlCTE AS
(
SELECT
ID,
Name = XC.value('(Name)[1]', 'varchar(100)'),
Value = XC.value('(Value)[1]', 'varchar(100)'),
DateReported = XC.value('(dateReported)[1]', 'datetime')
BB_ID = YourXmlColumn.value('(/XMLDoc/BB/ID)[1]', 'int'),
CC_Type = YourXmlColumn.value('(/XMLDoc/CC/Type)[1]', 'varchar(50)')
FROM
dbo.YourTable
CROSS APPLY
YourXmlColumn.nodes('/XMLDoc/AAA') AS XT(XC)
)
SELECT *
FROM XmlCTE
WHERE DateReported = (SELECT MAX(DateReported) FROM XmlCTE)
答案 1 :(得分:0)
在这种情况下可以使用SQL XML query
with cte as (
SELECT
t.id,
name.value('.','nvarchar(50)') as names,
dates.value('.','nvarchar(50)') as dates
FROM t
CROSS APPLY Col.nodes('/XMLDoc/AAA') as XMLtable1(AAA)
CROSS APPLY XMLtable1.AAA.nodes('Name') as XMLtable2(name)
CROSS APPLY XMLtable1.AAA.nodes('dateReported') as XMLtable3(dates)
)
select *
from (
select
*,
rn = ROW_NUMBER() over (partition by id order by dates desc)
from cte
) t where rn = 1
答案 2 :(得分:0)
对于更新后的要求,以下SQL Server XML query可以提供帮助 请测试表中多行的查询,以获得更准确的测试结果
;with cte as (
SELECT
t.id,
b.value('.','nvarchar(500)') as bbid,
c.value('.','nvarchar(500)') as cc,
name.value('.','nvarchar(50)') as names,
dates.value('.','nvarchar(50)') as dates
FROM t
CROSS APPLY Col.nodes('/XMLDoc/BB/ID') as XMLtable4(b)
CROSS APPLY Col.nodes('/XMLDoc/CC') as XMLtable5(c)
CROSS APPLY Col.nodes('/XMLDoc/x') as XMLtable0(d)
CROSS APPLY XMLtable0.d.nodes('AAA') as XMLtable1(AAA)
CROSS APPLY XMLtable1.AAA.nodes('Name') as XMLtable2(name)
CROSS APPLY XMLtable1.AAA.nodes('dateReported') as XMLtable3(dates)
)
select *
from (
select
*,
rn = ROW_NUMBER() over (partition by id order by dates desc)
from cte
) t where rn = 1