我有一个查询,我需要声明一个变量并为其设置值。然后在基于其中一个列值(max_val
)的select语句中,如果变量值超过max_col
中的值,我将需要更改变量的值。基本查询如下所示:
Declare @variable int
Set @variable = x
select * from (
select
*,
row_number () over (partition by account_id, product order by revenue desc) as rk
from (
select *
from dataset
where account_id = 'abc'
and product = 'xyz'
and @variable between min_val and max_val
) x
) y
where y.rk =1;
在此查询中@variable > max_val
,则不会显示任何记录。但是,我想要包含一个条件,以便在上述条件匹配时,@variable
的值为max_val
。
答案 0 :(得分:0)
您可以在第二行之后引入,将正确的值放入@variable
:
select @variable = case
when max(max_val) > @variable then @variable
else max(max_val)
end
from dataset
where account_id = 'abc'
and product = 'xyz'