gpt4 book ai didi

mysql - 在 MySQL 中使用 IF 输出作为变量

转载 作者:行者123 更新时间:2023-11-29 06:59:21 24 4
gpt4 key购买 nike

我有一个表alpha有3列,其中id(INT)time1,time2(DATETIME)

现在我想计算从 2017-04-182017-05-24 每天有多少行,我尝试了此查询但失败了

SELECT IF(time1 < time2, time2, time1) AS d, COUNT(DATE(d)) FROM alpha 
WHERE time1 IS NOT NULL AND time2 IS NOT NULL
AND DATE(d) BETWEEN DATE('2017-04-18') AND DATE('2017-05-24')

数据

ID  TIME1                  TIME2
-----------------------------------------------
1, '2017-04-19 04:08:03', '2017-04-19 04:08:03'
2, '2017-04-19 04:08:03', '2017-05-19 04:08:03'
3, '2017-06-19 04:08:03', '2017-04-19 04:08:03'
4, '2017-06-19 04:08:03', '2017-06-20 04:08:03'
5, '2017-05-19 04:08:03', '2017-05-01 04:08:03'

预期结果

DAY         COUNT
---------------------
2017-04-19 1
2017-05-19 2

最佳答案

一种可能的解决方案:

  SELECT DATE(d), COUNT(DATE(d)) FROM (
SELECT IF(time1 < time2, time2, time1) AS d FROM alpha
WHERE time1 IS NOT NULL AND time2 IS NOT NULL
) AS t
WHERE DATE(d) BETWEEN DATE('2017-04-18') AND DATE('2017-05-24')
GROUP BY DATE(d);

或者我不喜欢:

SELECT IF(time1 < time2, time2, time1) AS d, COUNT(DATE(IF(time1 < time2, time2, time1))) FROM alpha 
WHERE time1 IS NOT NULL AND time2 IS NOT NULL
AND DATE(IF(time1 < time2, time2, time1)) BETWEEN DATE('2017-05-13') AND DATE('2017-05-15')
GROUP BY DATE(IF(time1 < time2, time2, time1));

关于mysql - 在 MySQL 中使用 IF 输出作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44149541/

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