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
    
  • 相关阅读:
    游戏开发制作流程详细介绍
    成为群体领袖
    别人的,值得借鉴的经验
    linux下iptabes配置详解
    Oracle tnsnames.ora
    同时展多个物料BOM List
    Oracle判断是否为数字或数字型字符串
    linux上的vnc配置
    Oracle 中的正则函数
    如何将 backordered 的SO# 重新发运?
  • 原文地址:https://www.cnblogs.com/yxym2016/p/14186775.html
Copyright © 2011-2022 走看看