2012-11-28 74 views
1

我有以下SQL查詢:提取從XML列的特定值

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不是所有與排有關的東西?我希望這是有道理的?

回答

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 
+0

感謝此作品完美,我可以問一個更多的問題嗎? – user1854183

+0

我會舉幾個例子,如果該行包含多個: – user1854183

+0

@ user1854183:當然,也請添加示例數據/ XML請 – gbn