如何在mysql中提取第一个日期和最后一个日期

时间:2020-09-23 08:33:25

标签: mysql

能帮我一下吗?我想从同一记录中提取第一个日期和最后一个日期,也要计算(*)填充的日期数和与最后一个日期(第一个日期)的天差,不包括零个日期。示例表和所需的输出如下:

Table1
-----------
id  date1      date2       date3        date4         
1  01/09/2020  02/09/2020  03/09/2020   05/09/2020    
2  02/09/2020  03/09/2020  00/00/0000   05/09/2020      
3  04/08/2020  00/00/0000  06/09/2020   00/00/0000 
4  11/09/2020  00/00/0000  00/00/0000   14/09/2020    
5  00/00/0000  02/09/2020  03/09/2020  00/00/0000     



Desired result
----------------------

id  count(*) first_date   Last_date   days_difference (last-first)
1    4        01/09/2020   05/09/2020  4
2    3        02/09/2020   05/09/2020  3 
3    2        04/08/2020   06/08/2020  2
4    2        11/09/2020   14/09/2020  3
5    2        02/09/2020   03/09/2020  1

谢谢。

correct syntax:

After inputs from many experts, here is correct syntax: 

select id, count(ndate) as  count, min(ndate) as first_date, max(ndate) as last_date, DATEDIFF(MAX(ndate), MIN(ndate)) `days_difference` from (
select id, ndate from (select id, date1 as ndate from table1
UNION ALL
select id, date2 as ndate from table1
UNION ALL
select id, date3 as ndate from table1
UNION ALL
select id, date4 as ndate from table1) a where ndate!='0000-00-00') as b group by id;

2 个答案:

答案 0 :(得分:1)

``` SELECT ID, (date1不为空)+(date2不为空)+(date3不为空)+(date4不为空)`count(*)`, LEAST(date1,date2,date3,date4)first_date, GREATEST(date1,date2,date3,date4)last_date, DATEDIFF(GREATEST(date1,date2,date3,date4),LEAST(date1,date2,date3,date4))`days_difference(last-first)` 从表1 ```
SELECT id, 
       COUNT(date1) `count(*)`,
       MIN(date1) first_date,
       MAX(date1) last_date,
       DATEDIFF(MAX(date1), MIN(date1)) `days_difference (last-first)`
FROM ( SELECT id, date1
       UNION ALL
       SELECT id, date2
       UNION ALL
       SELECT id, date3
       UNION ALL
       SELECT id, date4 ) subquery
GROUP BY id
       

答案 1 :(得分:1)

标准化的环境可能看起来如下:

id* date_ref* date      
 1         1  2020/09/01
 2         1  2020/09/02
 3         1  2020/08/04
 4         1  2020/09/11
 
 1         2  2020/09/02
 2         2  2020/09/03
 5         2  2020/09/02
 
 1         3  2020/09/03
 3         3  2020/09/06
 5         3  2020/09/03
 
 1         4  2020/09/05
 2         4  2020/09/05
 4         4  2020/09/14

* = (component of) PRIMARY KEY

从这里开始,对数据集的查询变得微不足道(甚至优雅)