mysql - 当列的值依赖于 SQL 中不同行的数据时,如何添加列?

标签 mysql sql postgresql

我有一张 table 。我想添加一个 flag 列,并在温度高于前一天的行上将其设置为 1,否则将其设置为 0 .

输入数据是:

id  m_date      temp
-----------------------
1   2019-04-01  20
2   2019-04-02  25
3   2019-04-03  [NULL]
4   2019-04-04  24
5   [NULL]      25
6   2019-04-02  25
-----------------------

期望的输出:

id  m_date      temp    flag
----------------------------
1   2019-04-01  20       0
2   2019-04-02  25       1
3   2019-04-03  [NULL]   0
4   2019-04-04  24       1
5   [NULL]      25       1
6   2019-04-02  25       0
----------------------------

最佳答案

if temperature of row is greater than previous day'

使用lag():

select t.*,
       (case when lag(temp) over (order by date) > temp
             then 1 else 0
        end)
from t;

这回答了你的问题。但是,它不会返回相同的结果,因为不清楚您的 NULL 值规则是什么。

关于mysql - 当列的值依赖于 SQL 中不同行的数据时,如何添加列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419060/

相关文章:

php - mysql结果只能看到好友id

MYSQL按特定时间的日期时间范围分组

mysql - 来自多个模型的包含、选择、排序、限制(单个查询)

mysql - 删除MySQL中两个单词之间的空格

hibernate - 大对象不能用于自动提交模式

mysql union all with aliases,语法错误

mysql - 如何让这个查询变得高效?

sql - BigQuery SQL 查询中的动态列名

mysql - NestJs Typeorm 会删除外键列,即使设置为非空

postgresql - 使: *** [pipeline_kafka.如此]错误1