SQL Server:通过select包装组内的项目

时间:2014-04-01 12:30:14

标签: sql sql-server group-by

我有一个包含以下内容的存储过程,到目前为止工作正常:

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>

我怎样才能实现每一对&#34; cat&#34;和&#34; groupCount&#34;在&#34; itemGroup&#34;中单独包装在生成的xml字符串?

非常感谢你提供任何帮助,蒂姆。

1 个答案:

答案 0 :(得分: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>