我有以下查询,该查询按每个月对每个所有者进行不同的项目计数
SELECT owner, Month(date) AS month, Count(DISTINCT( item )) AS cnt
FROM table_name
WHERE impact < 3
AND group IN ( 'Group1', 'Group2', 'Group3')
AND date >= '2019-01-01'
AND date <= '2019-05-02 23:59:59'
GROUP BY owner, month
ORDER BY owner, month;
这将为每个所有者每月产生不同项目的计数。我想要的是每个月累计每个所有者的不重复项目数。对于2月,我想要从1月到2月的每个所有者的不同项目计数。对于3月,我想要从1月到3月的每个所有者的不同项目计数,依此类推。有人可以帮忙吗?
答案 0 :(得分:0)
如果我的理解正确,您希望根据商品首次出现在所有者的首次的累计计数。在MySQL 8+中,您可以使用窗口函数:
SELECT owner, Month(date) AS month,
COUNT(*) as this_month_cnt,
SUM(COUNT(*)) OVER (PARTITION BY owner ORDER BY MONTH(date)) as running_cnt
FROM (SELECT t.owner, t.item, MIN(t.date) as date
FROM table_name
WHERE impact < 3 AND
group IN ( 'Group1', 'Group2', 'Group3') AND
date >= '2019-01-01' AND
date < '2019-05-03'
GROUP BY owner, item
) t
GROUP BY owner, month
ORDER BY owner, month;