我有以下sql查询:
select
I.N.value('@DRN', 'varchar(50)') as DRN,
I.N.value('@CR_GUID', 'varchar(50)') AS CR,
I.N.value('@DR_GUID', 'varchar(50)') AS DR,
I.N.value('@AMOUNT', 'money') as Amount,
I.N.value('@DATE', 'Date') as ProDate
from Table as T
cross apply T.column.nodes('/ITEMS/ITEM') as I(N)
目前它将带回一切,例如:
DRN CR DR Amount Prodate
12 2p1rf 684pb 4686.23 2012-11-14
12 586io fdc25 4686.23 2012-11-16
13 hnv7p 19i6f 1800.00 2012-11-20
14 cd7k0 9s2vc 570.50 2012-11-20
15 pm78s qw3d5 8500.00 2012-11-23
如何从结果中排除以下内容,这是来自xml列中的同一行?
DRN CR DR Amount Prodate
*12* 2p1rf 684pb 4686.23 2012-11-14
*12* 586io fdc25 4686.23 2012-11-16
我只希望查询带回xml列中一个项目的行而不是多个值。
谢谢
然后我如何只带回多个项目的第一个项目:
DRN CR DR Amount Prodate
*12* 2p1rf 684pb 4686.23 2012-11-14
*12* 586io fdc25 4686.23 2012-11-16
所以我想只看到日期为2012-11-14的项目,而不是与该行有关的所有内容?我希望这有道理吗?
答案 0 :(得分:2)
你应该可以在那个
上进行内联聚合和过滤SELECT
X.DRN, X.CR, X.DR, X.Amount, X.ProDate
FROM
(
SELECT
COUNT(*) OVER (PARTITION BY I.N.value('@DRN', 'varchar(50)')) AS CountPerDRN,
I.N.value('@DRN', 'varchar(50)') as DRN,
I.N.value('@CR_GUID', 'varchar(50)') AS CR,
I.N.value('@DR_GUID', 'varchar(50)') AS DR,
I.N.value('@AMOUNT', 'money') as Amount,
I.N.value('@DATE', 'Date') as ProDate
from
MyTable as T
cross apply
T.Mycolumn.nodes('/ITEMS/ITEM') as I(N)
) X
WHERE
X.CountPerDRN= 1
在添加问题后编辑
只需将内联聚合更改为窗口函数
在这种情况下,我选择了基于最低ProDate
SELECT
X.DRN, X.CR, X.DR, X.Amount, X.ProDate
FROM
(
SELECT
ROW_NUMBER() OVER (
PARTITION BY I.N.value('@DRN', 'varchar(50)')
ORDER BY I.N.value('@DATE', 'Date')
) AS rnPerDRN,
I.N.value('@DRN', 'varchar(50)') as DRN,
I.N.value('@CR_GUID', 'varchar(50)') AS CR,
I.N.value('@DR_GUID', 'varchar(50)') AS DR,
I.N.value('@AMOUNT', 'money') as Amount,
I.N.value('@DATE', 'Date') as ProDate
from
MyTable as T
cross apply
T.Mycolumn.nodes('/ITEMS/ITEM') as I(N)
) X
WHERE
X.rnPerDRN = 1