我有这张桌子:
id datetime company adset 1 2019-04-08 15:12:11 1 1 2 2019-04-08 14:04:32 2 1 3 2019-04-08 14:04:45 1 1 4 2019-04-07 23:29:55 2 2 5 2019-04-06 21:14:35 2 2
我正在尝试按日期从各公司获取广告集总数的最后30天。 我的子查询已经差不多了,但是我仍然需要分组或加入公司。
离此最近的国家仍算错公司了
SELECT
DATE(datetime),
COUNT(id) as `total_leads`,
COUNT(company) as `company`,
COUNT(adset) as `adset`
FROM `leads`
WHERE datetime between (CURDATE() - INTERVAL 1 MONTH ) AND CURDATE()
GROUP BY DATE(datetime), company
ORDER BY DATE(datetime) DESC
但是我的查询需要每个公司的列,我实际上得到的是结果:
DATE(datetime) total_leads company adset 2019-04-07 94 94 94 2019-04-06 104 104 104 2019-04-05 93 93 93
最终报告应类似于:
date total_leads c1_adset1 c2_adset1 c2_adset2 2019-04-08 15 5 7 3 2019-04-07 12 3 7 2 2019-04-06 10 3 3 4
如何从公司和每个广告集中按日期获取总潜在客户? 我必须按广告集分开,因为公司2使用广告集1和2,而公司1仅使用广告集1。
任何帮助将不胜感激!
答案 0 :(得分:1)
很难确切地说出确切的含义,因为您的预期结果与样本数据并不完全匹配,但是我怀疑您正在寻找条件汇总:
SELECT
DATE(datetime) AS `date`,
COUNT(*) as `total_leads`,
SUM(company = 1 AND adset = 1) AS `c1_adset1`,
SUM(company = 1 AND adset = 2) AS `c1_adset2,
SUM(company = 2 AND adset = 1) AS `c2_adset1`,
SUM(company = 2 AND adset = 2) AS `c2_adset2`
FROM `leads`
WHERE datetime between (CURDATE() - INTERVAL 1 MONTH ) AND CURDATE()
GROUP BY DATE(datetime)
ORDER BY `date` DESC
每个SUM()
实际上计算每天有多少条记录符合内部条件。