gpt4 book ai didi

Php、MySql、具有两个计数的单个查询

转载 作者:行者123 更新时间:2023-11-29 05:15:25 26 4
gpt4 key购买 nike

我需要在一个查询中执行两个不同的计数。

First Query: count number of transactions from today 30 days back.
Second Query: count number of transactions from last 60 until last 30 days.

我的第一个查询工作正常:

SELECT 
COUNT(*) AS sales
FROM
transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND STATUS = 1;

如何将第二个查询合并到上面的查询中?

最佳答案

您可以使用COUNTCASE WHEN:

SELECT 
COUNT(CASE WHEN DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) AS c1,
COUNT(CASE WHEN DATE(created) <= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) AS c2
FROM transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 60 DAY)
AND STATUS = 1;

UNION:

SELECT COUNT(*) AS sales 
FROM transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND STATUS = 1
UNION ALL
SELECT COUNT(*)
FROM transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 60 DAY)
AND DATE(created) < DATE_SUB(NOW(), INTERVAL 30 DAY)
AND STATUS = 1

关于Php、MySql、具有两个计数的单个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33587959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com