从每天的多个条件中选择计数日期

时间:2019-10-12 15:09:13

标签: mysql sql

我有很多优惠券。我想每天了解用户从每个广告系列中收到了多少张优惠券。但是我不能为每个选择行写类似assigned_date的内容

SELECT count(id)                                                  as number_of_coupons,
       DATE_FORMAT(assigned_date, '%d-%m-%Y')                     as date,
       (SELECT COUNT(id) FROM coupon WHERE campaign_id = 1 AND assigned_date=THIS MUST BE SOMETHING) as campaign_1,
       (SELECT COUNT(id) FROM coupon WHERE campaign_id = 2 AND assigned_date=THIS MUST BE SOMETHING) as campaign_2
FROM coupon
GROUP BY DATE_FORMAT(assigned_date, '%d-%m-%Y')
order by STR_TO_DATE(date, '%d-%m-%Y') DESC

因此结果将是类似的。如何获得此结果?

+-------------------+------------+-------------+-----------+
| number of coupons |    date    |  campaign_1 | campaign2 |
+-------------------+------------+-------------+-----------+
|               156 | 12-10-2019 |        6980 |       100 |
|               177 | 11-10-2019 |        6980 |       100 |
|                44 | 10-10-2019 |        6980 |       100 |
|                94 | 09-10-2019 |        6980 |       100 |
|                93 | 08-10-2019 |        6980 |       100 |
+-------------------+------------+-------------+-----------+

1 个答案:

答案 0 :(得分:0)

不知道您的数据结构是什么样子,我只能推测解决方案应该是什么。但是,我的猜测是您想要的查询如下:

SELECT COUNT(DISTINCT cv.id) as number_of_coupons,
       DATE_FORMAT(cv.assigned_date, '%d-%m-%Y') as date,
       SUM(CASE WHEN c.campaign_id = 1 THEN 1 ELSE 0 END) as campaign_1,
       SUM(CASE WHEN c.campaign_id = 2 THEN 1 ELSE 0 END) as campaign_2
FROM coupon_vault cv LEFT JOIN
     coupons c
     ON cv.coupon_id = c.coupon_id
GROUP BY DATE_FORMAT(cv.assigned_date, '%d-%m-%Y')
ORDER BY MIN(cv.assigned_date);

很有可能COUNT(DISTINCT)是不必要的,而COUNT()就足够了。

Postgres和MySQL(您的原始标记)对于SUM(CASE . . .)都有合理的选择。但是,您尚未指定数据库,因此我坚持在两个数据库中都可以使用的代码。