我是SQL的新手,需要创建一个存储过程,从表中取出所有项目+按类别对它们进行分组,并为每个类别添加计数。
到目前为止,我有以下所有项目正确但不按类别分组和计算(见下文)。 这里的问题是它单独列出所有项目,而不是将它们分组到相应的组下。 我假设我必须在这里嵌套选择,但不知道如何做到这一点。
有人可以帮助我吗?
我的存储过程:
CREATE PROCEDURE [dbo].[FetchRequests]
AS
BEGIN
SET NOCOUNT ON;
SELECT categoryX, itemID
COUNT(*) AS groupCount,
MAX(dateX) AS groupNewest
FROM LogRequests
WHERE logStatus = 'active'
GROUP BY categoryX, itemID
ORDER BY groupCount desc, categoryX
FOR XML PATH('categoryX'), ELEMENTS, TYPE, ROOT('ranks')
END
当前结果:
<ranks>
<categoryX>
<categoryX>Category 1</categoryX>
<itemID>ID 1</itemID>
<groupCount>1</groupCount>
<groupNewest>2013-11-21</groupNewest>
</categoryX>
<categoryX>
<categoryX>Category 2</categoryX>
<itemID>ID 2</itemID>
<groupCount>1</groupCount>
<groupNewest>2013-10-30</groupNewest>
</categoryX>
// ...
</ranks>
预期结果:
<ranks>
<categoryX>
<categoryX>Category 1</categoryX>
<groupCount>3</groupCount>
<groupNewest>2013-11-21</groupNewest>
<itemID>ID 1</itemID>
<itemID>ID 2</itemID>
<itemID>ID 3</itemID>
<categoryX>Category 2</categoryX>
<groupCount>4</groupCount>
<groupNewest>2013-10-15</groupNewest>
<itemID>ID 1</itemID>
<itemID>ID 2</itemID>
<itemID>ID 3</itemID>
<itemID>ID 4</itemID>
// ...
</categoryX>
</ranks>
非常感谢你提供任何帮助,蒂姆。
答案 0 :(得分:3)
select
lr.categoryX,
count(*) as groupCount,
max(lr.dateX) as groupNewest,
(
select t.ItemID
from LogRequests as t
where t.logStatus = 'active' and t.categoryX = lr.categoryX
for xml path(''), type
)
from LogRequests as lr
where lr.logStatus = 'active'
group by lr.categoryX
for xml path('categoryX'), root('ranks')