Case 语句给出了意想不到的输出
Case statement gives unexpected output
我有一个子查询生成这样的一些行:
| year | quarter | id | status |
|------|---------|----|--------|
| 2020 | 4 | 1 | no |
| 2021 | 1 | 1 | yes |
| | | | |
然后我想添加一个额外的列来跟踪状态变化。我试过这个:
select
*,
case
when (year = 2020 and quarter = 4 and status = 'no') and (year = 2021 and quarter = 1 and status = 'yes')
then 1 else 0
end as status_change_during_2021_q1
from(
...
...
) t
order by id, year, quarter
limit 50
但是,这是我得到的输出:
| year | quarter | id | status | status_change_during_2021_q1 |
|------|---------|----|--------|------------------------------|
| 2020 | 4 | 1 | no | 0 |
| 2021 | 1 | 1 | yes | 0 |
我不明白为什么 status_change...的第二行没有设置为 1...?
您正在尝试比较 跨 行的值。使用 lag()
:
(case when status = 'yes' and
lag(status) over (partition by id order by year, quarter) = 'no'
then 1 else 0
end)
你的版本不能做任何有用的事情,因为,例如,year
不能同时是2021
和2020
在同一行.
我有一个子查询生成这样的一些行:
| year | quarter | id | status |
|------|---------|----|--------|
| 2020 | 4 | 1 | no |
| 2021 | 1 | 1 | yes |
| | | | |
然后我想添加一个额外的列来跟踪状态变化。我试过这个:
select
*,
case
when (year = 2020 and quarter = 4 and status = 'no') and (year = 2021 and quarter = 1 and status = 'yes')
then 1 else 0
end as status_change_during_2021_q1
from(
...
...
) t
order by id, year, quarter
limit 50
但是,这是我得到的输出:
| year | quarter | id | status | status_change_during_2021_q1 |
|------|---------|----|--------|------------------------------|
| 2020 | 4 | 1 | no | 0 |
| 2021 | 1 | 1 | yes | 0 |
我不明白为什么 status_change...的第二行没有设置为 1...?
您正在尝试比较 跨 行的值。使用 lag()
:
(case when status = 'yes' and
lag(status) over (partition by id order by year, quarter) = 'no'
then 1 else 0
end)
你的版本不能做任何有用的事情,因为,例如,year
不能同时是2021
和2020
在同一行.