我有一张 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/