我有下表
WeekId CalendarDate
200 1993-06-26 00:00:00
200 1993-06-27 00:00:00
200 1993-06-28 00:00:00
200 1993-06-29 00:00:00
200 1993-06-30 00:00:00
200 1993-07-01 00:00:00
201 1993-10-02 00:00:00
... ...................
... ...................
我想在此处创建一个单独的列,称为 weekRange ,该列采用weekId的第一个日历日期和同一周ID的最后一个日历日期,结果为:
例如:对于weekId 200,weekRange为
1993-06-26 00:00:00 - 1993-07-01 00:00:00
非常感谢您的帮助。谢谢
答案 0 :(得分:2)
您可以通过weekId在子查询上使用内部联接来获取最小值和最大值
select m.WeekId, m.calendarDate, concat(t.min_date, ' - ' , t.max_date )
from my_table m
inner join (
select weekId
, min(calendarDate) min_date
, max(calendarDate) max_date
from my_table
group by weekId
) t on t.weekId = m.weekId
一旦更改了表,添加了weekRange列(如varchar)..
您可以使用更新
update my_table m1
inner join (
select weekId
, min(calendarDate) min_date
, max(calendarDate) max_date
from my_table
group by weekId
) t on t.weekId = m1.weekId
set m1.weekRange = concat(t.min_date, ' - ' , t.max_date )
,以及日期格式,如您的注释
更新my_table m1 内部联接(
select weekId
, min(calendarDate) min_date
, max(calendarDate) max_date
from my_table
group by weekId
) t on t.weekId = m1.weekId
set m1.weekRange = concat(date_forma(t.min_date, '%m/%d/%Y'),
' - ' , date_forma(t.max_date, '%m-%d-%Y') )