2014-04-01 129 views
0

包組內的項目我有一個包含其工作正常,到目前爲止以下存儲過程:(例子)SQL服務器:通過選擇

SELECT  cat, 
      COUNT(*) AS groupCount 
FROM  Log_PE 
WHERE  CONVERT(DATE, dateEsc, 120) >= 
       CONVERT(DATE, 
       CONVERT(VARCHAR(6), DATEADD(month, -1, GETDATE()), 112) 
       + '01', 112) 
GROUP BY cat 
ORDER BY groupCount desc, cat 
FOR XML PATH('ranking'), ELEMENTS, TYPE 

當前XML:

<ranking> 
    <cat>2</cat> 
    <groupCount>84</groupCount> 
    <cat>5</cat> 
    <groupCount>27</groupCount> 
    <cat>9</cat> 
    <groupCount>19</groupCount> 
</ranking> 

相反,我想得到:

<ranking> 
    <itemGroup> 
     <cat>2</cat> 
     <groupCount>84</groupCount> 
    </itemGroup> 
    <itemGroup> 
     <cat>5</cat> 
     <groupCount>27</groupCount> 
    </itemGroup> 
    <itemGroup> 
     <cat>9</cat> 
     <groupCount>19</groupCount> 
    <itemGroup> 
</ranking> 

我該如何實現每對「cat」和「groupCount」在結果xml字符串中的「itemGroup」中被分別包裝?非常感謝任何幫助,Tim。

回答

2

SQL Fiddle

MS SQL Server 2012的架構設置

create table Log_PE 
(
    cat int, 
    dateEsc datetime 
) 

insert into Log_PE values(2, '20150227') 
insert into Log_PE values(2, '20150227') 
insert into Log_PE values(2, '20150227') 
insert into Log_PE values(5, '20150227') 
insert into Log_PE values(5, '20150227') 

查詢1

select cat, 
     count(*) as groupCount 
from Log_PE 
where dateEsc >= dateadd(month, datediff(month, 0, getdate()) - 1, 0) 
group by cat 
order by groupCount desc, cat 
for xml path('itemGroup'), root('ranking'), type 

Results

<ranking> 
    <itemGroup> 
    <cat>2</cat> 
    <groupCount>3</groupCount> 
    </itemGroup> 
    <itemGroup> 
    <cat>5</cat> 
    <groupCount>2</groupCount> 
    </itemGroup> 
</ranking> 
+2

這樣做 - 非常感謝! – user2571510