SQL选择和日期范围(分组?)

时间:2015-09-02 12:56:42

标签: mysql sql date datetime select

您好?我通过SQL select

获得以下数据
+-----------------------------------------------------------+
|   Name              DateStart                DateEnd      |
+-----------------------------------------------------------+
| St Essai     2015-10-20 08:15:00      2015-10-20 10:15:00 |
| St Essai     2015-10-20 10:30:00      2015-10-20 12:30:00 |
| St Essai     2015-10-20 13:30:00      2015-10-20 15:30:00 |
| St Essai     2015-10-20 15:45:00      2015-10-20 17:45:00 |
| St Essai     2015-10-21 08:15:00      2015-10-21 10:15:00 |
| St Essai     2015-10-21 10:30:00      2015-10-21 12:30:00 |
| St Essai     2015-10-21 13:30:00      2015-10-21 15:30:00 |
| St Essai     2015-10-21 15:45:00      2015-10-21 17:45:00 |
+-----------------------------------------------------------+

如你所见,我一天有4行。我想改为

+-----------------------------------------------------------+
|  Name              DateStart                DateEnd       |
+-----------------------------------------------------------+
| St Essai     2015-10-20 08:15:00      2015-10-20 17:45:00 |
| St Essai     2015-10-21 08:15:00      2015-10-21 17:45:00 |
+-----------------------------------------------------------+

第一行是NAME,第二行是DATE START,最后一行是DATE END

因此,不是一天中的4行,而只是重新组合4个日期。

如果有4行(代表一整天),是否可以只有这一行。

非常感谢!

5 个答案:

答案 0 :(得分:1)

list = system("echo $(dir *.dat)")
plot for [1:i] i using 1:((2*i)+(column(2))) w steps tit i

答案 1 :(得分:0)

按名称分组并取最小最大值

select NAME, min(DATE_START), max(DATE_END) from thetable group by NAME, date(DATE_START)

答案 2 :(得分:0)

试试这个

select name,min(date) as date_from, max(date) as date_to from table
group by name

答案 3 :(得分:0)

你去了{p> Here。我已经创建了一个看起来像你的表,并且复杂数据只是为了更好地测试它。想法是每天查找最小和最大小时数并将它们连接成一行。

select minTable.minhour , maxTable.maxhour, maxTable.name
from (select  min(startdate) as minhour, date(startdate) as aday, name from ATable
group by aday, name) minTable 
join 
(select  max(enddate) as maxhour, date(enddate) as aday , name from ATable
group by aday, name) maxTable
on minTable.aday = maxTable.aday and minTable.name = maxTable.name

或更简单......

select  min(startdate) , max(enddate), name from ATable
group by date(startdate), name

答案 4 :(得分:0)

您只需在群组中添加date(datestart)

select name,
       min(datestart) as  datestart,
       max(dateend) as  dateend
   from mytable
   group by name,date(datestart);

SQL Fiddle Demo