zoukankan      html  css  js  c++  java
  • SQL练习20201224

    197.上升的温度

    表 Weather

    +---------------+---------+
    | Column Name   | Type    |
    +---------------+---------+
    | id            | int     |
    | recordDate    | date    |
    | temperature   | int     |
    +---------------+---------+
    

    id是这个表的主键
    该表包含特定日期的温度信息

    编写一个SQL查询,来查找与之前(昨天的)日期相比温度更高的所有日期的id。返回结果不要求顺序

    查询结果格式如下:

    Weather
    +----+------------+-------------+
    | id | recordDate | Temperature |
    +----+------------+-------------+
    | 1  | 2015-01-01 | 10          |
    | 2  | 2015-01-02 | 25          |
    | 3  | 2015-01-03 | 20          |
    | 4  | 2015-01-04 | 30          |
    +----+------------+-------------+
    
    Result table:
    +----+
    | id |
    +----+
    | 2  |
    | 4  |
    +----+
    2015-01-02 的温度比前一天高(10 -> 25)
    2015-01-04 的温度比前一天高(20 -> 30)
    

    解决方法1,窗口函数:

    ​ datediff函数,datediff(date1,date2) 作用是两个日期相减,返回date1-date2的天数。

    select a.id as id
    from(
    select id,recordDate,Temperature,
    lag(recordDate,1) over(order by recordDate) as lastday
    ,lag(Temperature,1) over(order by recordDate) as lastTemper
    from Weather ) a
    where a.Temperature>a.lastTemper and datediff(a.recordDate,lastday)=1
    

    解决方法2,左连接+date_sub函数

    select w1.id
    from Weather w1 
    left join Weather w2 on  date_sub(w1.recordDate, interval 1 day) = w2.recordDate 
    where w1.Temperature > w2.Temperature
    
  • 相关阅读:
    【转】Windows Server 2003为什么识别不了的移动硬盘
    VBSCRIPT常用函数【转】
    【轉】javascript实现图片缩略与优化
    【转】Tips:禁用Windows Beep声
    EXT同struts2后台交互一个中文问题
    ASCII码对照表[转]
    bat判断进程存在不存在
    look与look like
    美国俚语there was no snap in his turtle
    take credit for用法
  • 原文地址:https://www.cnblogs.com/yxym2016/p/14186775.html
Copyright © 2011-2022 走看看