在“联合”表上按日期计数实例

时间:2019-08-18 20:43:43

标签: sql presto

假设我有两个表:DatesActions

我想根据为Dates表选择的所有日期计算出多少操作。

我正在像这样拉日期表:

SELECT DISTINCT
    dateid
FROM
    dates
WHERE 
    DATE(dateid) BETWEEN DATE('2019-01-01') and CURRENT_DATE

在我的Actions表上,我有字段action_date。我想计算action_date

中出现dates的次数

上面的查询生成的日期表

+-------+
| Dateid|
+-------+
| Jan 1 |
+-------+
| Jan 2 |
+-------+
| Jan 3 |
+-------+
| Jan 4 |
+-------+

按日期列出的操作表

+-------------+
| Action_Date |
+-------------+
| Jan 1       |
+-------------+
| Jan 1       |
+-------------+
| Jan 1       |
+-------------+
| Jan 2       |
+-------------+
| Jan 3       |
+-------------+
| Jan 3       |
+-------------+
| Jan 3       |
+-------------+
| Jan 3       |
+-------------+

所需的输出

+-------------+-------+
| Action_Date | Count |
+-------------+-------+
| Jan 1       | 3     |
+-------------+-------+
| Jan 2       | 1     |
+-------------+-------+
| Jan 3       | 4     |
+-------------+-------+
| Jan 4       | 0     |
+-------------+-------+

2 个答案:

答案 0 :(得分:1)

(表名和列名可能需要调整)

SELECT a.ActionDate, COUNT(*)
FROM Action_Date a JOIN DateTable dt ON a.ActionDate = dt.dateid
GROUP BY a.ActionDate

答案 1 :(得分:1)

您似乎想要一个left join

SELECT d.dateid as ActionDate, COUNT(a.ActionDate)
FROM Dates d LEFT JOIN
     Actions a 
     ON a.ActionDate = dt.dateid
WHERE DATE(dateid) BETWEEN DATE('2019-01-01') AND CURRENT_DATE
GROUP BY d.dateid
ORDER BY DATE(d.dateid);