mysql查询天数并计算日期之间的天数

时间:2019-08-01 07:51:07

标签: mysql sql

我需要获取天数之间的ID和天数。

INSERT INTO Events
    (`ID`, `START`, `END`)
VALUES
    (2313, '2019-07-29', '2019-08-10'),
    (41, '2019-06-22', '2019-07-01'),
    (2540, '2019-06-22', '2019-07-02'),
    (2234, '2019-06-28', '2019-07-12'),
    (2634, '2019-06-30', '2019-07-04'),
    (53, '2019-06-30', '2019-07-02'),
    (1869, '2019-06-30', '2019-07-15'),
    (2132, '2019-07-30', '2019-08-10')
;

我的查询是

SELECT `ID`
  FROM Events 
 WHERE `START` BETWEEN '2019-07-01' AND '2019-07-31' 
   AND `END` BETWEEN '2019-07-01' AND '2019-07-31';

我需要输出为

2313 - 3
41 - 1
2540 - 2
2234 - 12
.....

请帮助我。

2 个答案:

答案 0 :(得分:4)

GREATEST返回列表中的最大值,至少-min

select ID, 
       DATEDIFF(LEAST(`END`,'2019-07-31'), GREATEST(`START`, '2019-07-01')) + 1
from events

答案 1 :(得分:1)

使用DATEDIFF()函数。

public static void main(String args[]){
    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt(); // a = -15
    int n = scanner.nextInt(); // cycle = 12

    int reminder = a - (n * Math.toIntExact(a / n));
    int reminder_plus_n = (reminder + n);
    int modulo = reminder_plus_n - (n * Math.toIntExact(reminder_plus_n / n));
    System.out.println(modulo); // Answer = 9
}