0

此查询获取所需的行 - 按主题分组 - 我还想知道每个组中的项目数。

SELECT log.* FROM [hm_deliverylog] AS log
WHERE log.deliveryid IN
    (
        SELECT MAX([deliveryid])  FROM [hm_deliverylog]
        WHERE [deliverytime] > DATEADD(HOUR, -12, GETDATE())
        GROUP BY deliverysubject
    )

ORDER BY deliveryid DESC

我如何计算组?像下面这样?

SELECT joined.groupcount, log.* FROM [hm_deliverylog] AS log

PS:想象一下 Gmail 收件箱;它显示最新消息并显示消息计数。我想将具有相同主题的消息分组并计算它们...

4

3 回答 3

1

您可以使用OVER子句

SELECT COUNT(deliveryid) OVER (PARTITION BY deliverysubject) As GroupCount

在应用关联的窗口函数之前确定行集的分区和排序。也就是说,OVER 子句在查询结果集中定义了一个窗口或用户指定的一组行。然后窗口函数为窗口中的每一行计算一个值。您可以将 OVER 子句与函数一起使用来计算聚合值,例如移动平均值、累积聚合、运行总计或每组结果的前 N ​​个。

于 2012-11-08T11:53:23.933 回答
1

一种方法是将COUNT()计算放在子查询中,而不是使用IN,将派生表连接起来:

SELECT log.* 
     , grp.cnt AS groupcount
FROM 
    [hm_deliverylog] AS log
  JOIN 
    (
        SELECT MAX([deliveryid]) AS deliveryid
             , COUNT(*) AS cnt  
        FROM [hm_deliverylog]
        WHERE [deliverytime] > DATEADD(HOUR, -12, GETDATE())
        GROUP BY deliverysubject
    ) AS grp
    ON grp.deliveryid = log.deliveryid
ORDER BY 
    log.deliveryid DESC ;
于 2012-11-08T12:02:24.347 回答
0
SELECT log.*, COUNT(*) OVER (PARTITION BY deliverysubject) AS groupcount 
FROM [hm_deliverylog] AS log
GROUP BY deliverysubject
于 2012-11-08T11:59:45.213 回答