有没有一种方法可以在此MYSQL查询中找到总和和累计计数?

时间:2020-04-24 18:31:07

标签: mysql sql database sum window-functions

我使用这个MYSQL查询来查找表groups在其关联表members中随时间的累积增长。

  SELECT DISTINCT g.name, m.created_at,
           COUNT(*) OVER(PARTITION by g.id ORDER BY m.created_at) count
    FROM members m
    INNER JOIN groups g on g.id = m.group_id

这给出了如下结果集:

[
  { 'group01', date: '2019-03-04', count: 5 },
  { 'group01', date: '2019-03-09', count: 12 }
  { 'group01', date: '2019-03-15', count: 23 }
  { 'group02', date: '2019-03-04', count: 3 }
  { 'group01', date: '2019-03-10', count: 19 }
  { 'group01', date: '2019-03-17', count: 27 }
]

我还将检索小组成员的总数。这样数据集将如下所示:

[
  { name: 'group01', date: '2019-03-04', count: 5, total: 23 },
  { name: 'group01', date: '2019-03-09', count: 12, total: 23 },
  { name: 'group01', date: '2019-03-15', count: 23, total: 23 },
  { name: 'group02', date: '2019-03-04', count: 3, total: 27 },
  { name: 'group02', date: '2019-03-10', count: 19, total: 27 },
  { name: 'group02', date: '2019-03-17', count: 27, total: 27 }
]

我需要这样做,以便以后我可以轻松地订购和找到会员人数最多的团体。

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

只需将另一列添加到结果集中,该列将对相同的partition进行窗口计数,但没有order by子句;这将导致数据库计算分区中的总行数:

SELECT g.name, m.created_at,
       COUNT(*) OVER(PARTITION by g.id ORDER BY m.created_at) count,
       COUNT(*) OVER(PARTITION by g.id) total
FROM members m
INNER JOIN groups g on g.id = m.group_id

注意:我对DISTINCT子句中的SELECT的使用感到怀疑,因此我将其删除(尽管在某些情况下,将其与窗口函数一起使用几乎没有任何意义)-您可以根据需要将其重新添加。

答案 1 :(得分:0)

我将使用显式聚合来编写它:

SELECT g.name, m.created_at,
       SUM(COUNT(*)) OVER (PARTITION BY g.id ORDER BY m.created_at) as count_on_day,
       SUM(COUNT(*)) OVER (PARTITION BY g.id) as count_for_group
FROM members m INNER JOIN
     groups g 
     ON g.id = m.group_id
GROUP BY g.name, m.created_at