2017-04-22 53 views
2

我在下面有一個sql查詢,我想使用FOR XML語法將其格式化爲XML。使用FOR XML對2個sql表進行分組

SELECT 
    gr.id, 
    gr.created, 
    ts.ordernumber 
FROM trGrouped gr 
INNER JOIN transactions ts 
    ON ts.grouped_id = gr.id 
WHERE ts.ordernumber IN ('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018') 

這是我希望查詢看起來像XML格式的一個例子。

<trans_groups> 
    <grouped id="56" created="4/14/2017"> 
    <ordernumber>1022108100000001</ordernumber> 
    <ordernumber>1022108100000002</ordernumber> 
    <ordernumber>1022108100000003</ordernumber> 
    </grouped> 
    <grouped id="57" created="4/14/2017"> 
    <ordernumber>1022109100000001</ordernumber> 
    <ordernumber>1022109100000002</ordernumber> 
    </grouped> 
</trans_groups> 

到目前爲止,我還沒有能夠得到這個正確的。我已經嘗試了以下內容,但這不會將訂單分組。

select gr.id as [@id], gr.created as [@created], 
    (
    SELECT ts.ordernumber as ordernumber 
    ) 
FROM trGrouped gr inner join transactions ts on ts.grouped_id = gr.id 
    where ts.ordernumber in('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018') 
FOR XML PATH('grouped'), ROOT('trans_groups') 

回答

3

這是一種方法

Declare @YourTable table (id int,created date, ordernumber varchar(25)) 
Insert Into @YourTable values 
(56,'04/14/2017','1022108100000001') 
,(56,'04/14/2017','1022108100000002') 
,(56,'04/14/2017','1022108100000003') 
,(57,'04/14/2017','1022109100000001') 
,(57,'04/14/2017','1022109100000002') 

Select [@id]  = id 
     ,[@created] = convert(VARCHAR(10), created, 101) 
     ,(
     Select ordernumber 
     From @YourTable A1 
     Where A1.id = A.id 
     For XML Path(''), type 
     ) 
From (Select Distinct ID,Created From @YourTable) A 
For XML Path('grouped'), Root('trans_groups') 

返回

<trans_groups> 
    <grouped id="56" created="04/14/2017"> 
    <ordernumber>1022108100000001</ordernumber> 
    <ordernumber>1022108100000002</ordernumber> 
    <ordernumber>1022108100000003</ordernumber> 
    </grouped> 
    <grouped id="57" created="04/14/2017"> 
    <ordernumber>1022109100000001</ordernumber> 
    <ordernumber>1022109100000002</ordernumber> 
    </grouped> 
</trans_groups> 
+0

非常好!一般來說,「選擇不同的派生表」與「按ID創建的組」有區別嗎? http://rextester.com/ZLS77092 – SqlZim

+1

@SqlZim在更大的數據集上,我發現DISTINCT更快,沒有多少,但顯而易見。這可能是部落知識,所以我將重新審視,並稍微運行一些基準。 –

+1

@SqlZim對於80,000條記錄的樣本大小,DISTINCT的平均運行時間爲327ms,而GROUP BY爲412MS –

0

這是爲我工作。

select gr.id as [@id], gr.created as [@created], 
    (
    SELECT ordernumber as ordernumber from transactions where grouped_id = grouped_id 
    and ordernumber in ('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018') 
    FOR XML path(''), type 
    ) 
FROM (SELECT distinct gr.id, created FROM trGrouped gr inner join transactions ts on ts.grouped_id = gr.id 
    where ts.ordernumber in('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018')) gr 
FOR XML PATH('grouped'), ROOT('trans_groups')