1

我有以下 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 的项目,而不是与该行有关的所有内容?我希望这是有道理的?

4

1 回答 1

2

You should be able to do an inline aggregate and filter on that

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

Edit, after question addition

Simply change the inline aggregate to a window function
In this case, I've chosen the row based on the lowest 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
于 2012-11-28T08:03:54.970 回答