我有一种情况,在这种情况下,我必须使用一个条件条件,在该条件下,如果值匹配,则需要从表中获取值,否则需要将其硬编码为1和0。
表结构:许可证
------------------------------------
Number permit reviewpermit State
101 0 1 TX
101 1 0 OK
101 1 1 NC
102 1 1 LA
102 0 1 OK
条件:
Number permit reviewpermit State
101 0 1 TX
101 0 1 OK
101 0 1 NC
102 1 0 LA
102 1 0 OK
101组具有所有得克萨斯州的许可和审查许可值102组的所有许可和复查许可值分别为“ 1”和“ 0”。
我到目前为止编写的代码。
select Number,
MAX(CASE WHEN State = 'TX' THEN Permit ELSE 1 END) OVER (PARTITION BY [Number])as permit,
MAX(CASE WHEN State = 'TX' THEN ReviewPermit ELSE 0 END) OVER (PARTITION BY [Number]) AS reviewpermit, state
from License
但是它没有给我想要的输出。
我认为此逻辑可以满足您的要求:
select Number,
coalesce(MAX(CASE WHEN State = 'TX' THEN Permit END) OVER (PARTITION BY [Number]),
1) as permit,
coalesce(MAX(CASE WHEN State = 'TX' THEN ReviewPermit END) OVER (PARTITION BY [Number]),
0) AS reviewpermit, state
from License;
此检查MAX()
中的“德州”。如果不存在,则值为NULL
,因此COALESCE()
会采用默认值。
将表加入到查询中,该查询通过按[Number]分组返回将设置到每一行的值的类型:
select t.[Number],
case when type = 1 then g.permit else 1 end permit,
case when type = 1 then g.reviewpermit else 0 end reviewpermit,
t.[State]
from License t inner join (
select [Number],
max(case when [State] = 'TX' THEN permit END) permit,
max(case when [State] = 'TX' THEN reviewpermit END) reviewpermit,
max(case when [State] = 'TX' THEN 1 END) type
from License
group by [Number]
) g on g.[Number] = t.[Number]
请参见demo。结果:
> Number | permit | reviewpermit | State
> -----: | -----: | -----------: | :----
> 101 | 0 | 1 | TX
> 101 | 0 | 1 | OK
> 101 | 0 | 1 | NC
> 102 | 1 | 0 | LA
> 102 | 1 | 0 | OK