datediff(当前日期,更新时间)为diff,count(*)

arknldoa  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(336)

我只是不能把我的头绕在这上面:(
我试图从我的专栏“diff”中输出3个不同的结果
<1<3和<7
以下是我目前的疑问:

SELECT DATEDIFF(CURRENT_DATE, updated_at) AS Diff, COUNT(*) FROM Table GROUP BY Diff

但实际上我只需要输出3列,数量<1,<3和<7
我希望有人能帮忙

jv4diomz

jv4diomz1#

使用条件聚合:

SELECT
    COUNT(CASE WHEN DATEDIFF(CURRENT_DATE, updated_at) < 1 THEN 1 END) AS diff_lt_1,
    COUNT(CASE WHEN DATEDIFF(CURRENT_DATE, updated_at) >= 1 AND
                    DATEDIFF(CURRENT_DATE, updated_at) < 3 THEN 1 END) AS diff_1_to_3,
    COUNT(CASE WHEN DATEDIFF(CURRENT_DATE, updated_at) >= 3 AND
                    DATEDIFF(CURRENT_DATE, updated_at) < 7 THEN 1 END) AS diff_3_to_7,
    COUNT(CASE WHEN DATEDIFF(CURRENT_DATE, updated_at) >= 7 THEN 1 END) AS diff_gt_7
FROM Table;

实际上还不清楚你应该在哪一列做文章 GROUP BY . 我们可以修改上面的查询,如果您显示的样本数据显示您正在尝试做什么。

相关问题