在mysql中获取一周的最后一个值

时间:2018-03-28 15:03:13

标签: mysql sql

我想知道如何获得每周的最后一个值。

假设我有下一个值

-- Table 1 --
day          value
2018-03-12   32
2018-02-14   42
2018-03-16   62
2018-03-19   82
2018-03-20   92
2018-03-21   102
2018-03-27   112
2018-03-28   122
2018-03-29   132

如何获取下一个值,这些值是每周的最后一个值。假设星期一开始一周。

Day        Value
2018-03-16 62
2018-03-21 102
2018-03-29 132

我已经解决了所有问题SQL Fiddle

5 个答案:

答案 0 :(得分:3)

您可以获取星期数,然后获取每周最大值数。

select t1.*
from table1 t1
join (
select week(day) as wknum, 
       max(day) as day
from   table1 
group by week(day)
     ) t2
on t1.day=t2.day


Result:
day         value
2018-03-16  62
2018-03-21  102
2018-03-29  132

答案 1 :(得分:1)

此解决方案使用窗口函数并选择一周内的最新日期。

https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html

我使用SQL Server,但我相信这是MySQL的等价物:

with cte AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY WEEKOFYEAR([day]) ORDER BY DAYOFWEEK([day]) DESC) AS counter_
from #table1 
)

SELECT [day], [value] 
FROM cte 
WHERE counter_ = 1

答案 2 :(得分:1)

以下是如何在SQL Server中执行此操作 - 使用等效的mysql

select b.day, b.value from (
select datepart(ww,day) a, max(day) b
from yourtable
group by datepart(ww,day))a
join yourtable b on a.a=datepart(ww,b.day) and a.b=b.day

答案 3 :(得分:1)

您可以按YEARWEEK()

进行分组
create table tbl (day date, value int);
insert into tbl values
('2018-03-12',   32),
('2018-02-14',   42),
('2018-03-16',   62),
('2018-03-19',   82),
('2018-03-20',   92),
('2018-03-21',   102),
('2018-03-27',   112),
('2018-03-28',   122),
('2018-03-29',   132);
select day, yearweek(day) from tbl;
day        | yearweek(day)
:--------- | ------------:
2018-03-12 |        201810
2018-02-14 |        201806
2018-03-16 |        201810
2018-03-19 |        201811
2018-03-20 |        201811
2018-03-21 |        201811
2018-03-27 |        201812
2018-03-28 |        201812
2018-03-29 |        201812
select day, value
from tbl
join (select max(day) mday
      from   tbl
      group by yearweek(day)) t
on day = mday
day        | value
:--------- | ----:
2018-02-14 |    42
2018-03-16 |    62
2018-03-21 |   102
2018-03-29 |   132

dbfiddle here

答案 4 :(得分:1)

试试这个FIDDLE

=按最接近每周结束的顺序排序

=按周分组

SELECT day, value
FROM (SELECT * FROM table1 ORDER BY DATEDIFF(day + INTERVAL 6 - weekday(day) DAY, day) ASC) t
GROUP BY week(day);