[英]SQL count data from beginning of the date till current month/year
我有从 2019 年 3 月到 2020 年 2 月的客户数据。我正在计算用于购买机票的电子邮件总数,然后是每个月,我使用的查询是
SELECT sub.monthNameYear,sub.monthName,count(*) from
(SELECT DATE_FORMAT(`reservation_for`,'%Y-%m') as monthNameYear,DATE_FORMAT(`reservation_for`,'%M %Y') as monthName,
email,
COUNT(*) AS 'Count'
FROM `tablename`
GROUP BY email, DATE_FORMAT(`reservation_for`, '%Y-%m')
HAVING COUNT(*) > 1
ORDER BY DATE_FORMAT(`reservation_for`, '%Y-%m') ) as sub
GROUP BY sub.monthNameYear;
我想要的结果附在下面。 它总是选择日期的开始,然后选择每个月,然后只计算电子邮件总数。
如果您运行的是 MySQL 8.0,则可以进行窗口求和。 从您现有的查询开始:
SELECT
monthNameYear,
monthName,
SUM(COUNT(*)) OVER(ORDER BY monthNameYear) totalPurchase
FROM (
SELECT
DATE_FORMAT(`reservation_for`,'%Y-%m') monthNameYear,
DATE_FORMAT(`reservation_for`,'%M %Y') monthName,
email
FROM `tablename`
GROUP BY monthNameYear, monthName, email
HAVING COUNT(*) > 1
) as sub
GROUP BY monthNameYear, monthName
ORDER BY monthNameYear;
笔记:
总是枚举group by
子句中的所有非聚合列
order by
子句应该放在外部查询中
您COUNT(*) in the subquery, but it is not used in the outer query - I removed that column from the
中select
COUNT(*) in the subquery, but it is not used in the outer query - I removed that column from the
select` 子句中COUNT(*) in the subquery, but it is not used in the outer query - I removed that column from the
您可以使用窗口函数:
SELECT ed.monthNameYear, ed.monthName,
COUNT(*),
SUM(COUNT(*)) OVER (ORDER BY ed.monthNameYear)
FROM (SELECT DATE_FORMAT(`reservation_for`,'%Y-%m') as monthNameYear,
DATE_FORMAT(`reservation_for`, '%M %Y') as monthName,
email,
COUNT(*) AS cnt
FROM `tablename`
GROUP BY email, DATE_FORMAT(`reservation_for`, '%Y-%m'),
DATE_FORMAT(`reservation_for`,'%M %Y')
HAVING COUNT(*) > 1
) ed
GROUP BY ed.monthNameYear, ed.monthName;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.