将mysql中同一表的行值与条件进行比较
我有这样的数据:将mysql中同一表的行值与条件进行比较,mysql,sql,Mysql,Sql,我有这样的数据: header_id | class | start_date | end_date ------------------------------------------- 1 | c1 | 20-08-2019 | 22-08-2019 1 | c1 | 22-08-2019 | 24-08-2019 1 | c2 | 24-08-2019 | 27-08-2019 2 | c3 | 21-
header_id | class | start_date | end_date
-------------------------------------------
1 | c1 | 20-08-2019 | 22-08-2019
1 | c1 | 22-08-2019 | 24-08-2019
1 | c2 | 24-08-2019 | 27-08-2019
2 | c3 | 21-08-2019 | 22-08-2019
2 | c2 | 22-08-2019 | 25-08-2019
2 | c3 | 25-08-2019 | 26-08-2019
SELECT header_id,class,MIN(st_date),MAX(en_date) FROM
(SELECT a.header_id,a.class,
LEAST(IFNULL(a.start_date,b.start_date),IFNULL(b.start_date,a.start_date)) AS st_date,
GREATEST(IFNULL(a.end_date,b.end_date),IFNULL(b.end_date,a.end_date)) AS en_date
FROM testing a
LEFT JOIN testing b ON a.header_id=b.header_id
AND a.class=b.class
AND a.start_date=b.end_date) A
GROUP BY header_id,class,st_date
ORDER BY header_id,class,st_date;
我希望得到以下结果:
header_id | class | start_date | end_date
-------------------------------------------
1 | c1 | 20-08-2019 | 24-08-2019
1 | c2 | 24-08-2019 | 27-08-2019
2 | c3 | 21-08-2019 | 22-08-2019
2 | c2 | 22-08-2019 | 25-08-2019
2 | c3 | 25-08-2019 | 26-08-2019
如果header_id相同,class相同,并且之前数据的结束日期与之后数据的开始日期相同,则它将取开始日期的最小日期和结束日期的最大日期。但是,如果之前数据的结束日期与之后数据的开始日期不同,则数据将正常显示
有没有办法得到这个结果?使用
范例
也许这可以通过使用聚合函数
min
和max
实现:
SELECT header_id, class, min(start_date) as start_date, max(end_date) as end_date
FROM table_name
Group by header_id, class
这有点棘手,但是您可以
左连接表本身,然后使用最小值
、最大值
和最小值最大值
函数的组合,如下所示:
header_id | class | start_date | end_date
-------------------------------------------
1 | c1 | 20-08-2019 | 22-08-2019
1 | c1 | 22-08-2019 | 24-08-2019
1 | c2 | 24-08-2019 | 27-08-2019
2 | c3 | 21-08-2019 | 22-08-2019
2 | c2 | 22-08-2019 | 25-08-2019
2 | c3 | 25-08-2019 | 26-08-2019
SELECT header_id,class,MIN(st_date),MAX(en_date) FROM
(SELECT a.header_id,a.class,
LEAST(IFNULL(a.start_date,b.start_date),IFNULL(b.start_date,a.start_date)) AS st_date,
GREATEST(IFNULL(a.end_date,b.end_date),IFNULL(b.end_date,a.end_date)) AS en_date
FROM testing a
LEFT JOIN testing b ON a.header_id=b.header_id
AND a.class=b.class
AND a.start_date=b.end_date) A
GROUP BY header_id,class,st_date
ORDER BY header_id,class,st_date;
请参阅此处的fiddle: