将查询结果分配给变量以用于 case 语句
Assign Results from query to variable for use in case statement
我正在尝试获取总样本列的平均值,并与每个特定记录的列值进行比较。
我在 SQL 服务器中通过声明一个变量然后将其设置为查询结果来完成此操作。
我想在 PG 中做同样的事情,但我没有成功。
在下面的示例中,myconstant2
由于硬编码值而有效,但 myconstant
无效,因为该值设置为单行查询结果。
这里有任何指示吗?
with myconstant (var1) as
(
values (select AVG(ptb_account_score_c)
from salesforce_production.accounts)
),
myconstant2 (var2) as
(
values(6)
)
select
Id,
ptb_account_score_c,
var1,
var2,
case
when ptb_account_score_c > var1 then 1 else 0
end as Blah
from
salesforce_production.accounts, myconstant, myconstant2
你不需要values
:
WITH
myconstant1 as (select AVG(ptb_account_score_c) as val from salesforce_production.accounts),
myconstant2 as (select 6 as val)
SELECT Id, ptb_account_score_c, myconstant1.val,
myconstant2.val,
case when ptb_account_score_c > myconstant1.val then 1 else 0 end as Blah
FROM salesforce_production.accounts,myconstant1,myconstant2
我想你只是想要一个 window 函数:
select a.*,
(case when ptb_account_score_c > avg(a.ptb_account_score_c) over () then 1 else 0 end) as Blah
from salesforce_production.accounts a;
如果需要,您可以将这些组合成一个 CTE:
with params as (
select AVG(ptb_account_score_c) as var1, 6 as var2
from salesforce_production.accounts
)
select a.id, a.ptb_account_score_c,
params.var1, params.var2,
(case when a.ptb_account_score_c > params.var1 then 1 else 0 end) as Blah
from salesforce_production.accounts a cross join
params;
我正在尝试获取总样本列的平均值,并与每个特定记录的列值进行比较。
我在 SQL 服务器中通过声明一个变量然后将其设置为查询结果来完成此操作。
我想在 PG 中做同样的事情,但我没有成功。
在下面的示例中,myconstant2
由于硬编码值而有效,但 myconstant
无效,因为该值设置为单行查询结果。
这里有任何指示吗?
with myconstant (var1) as
(
values (select AVG(ptb_account_score_c)
from salesforce_production.accounts)
),
myconstant2 (var2) as
(
values(6)
)
select
Id,
ptb_account_score_c,
var1,
var2,
case
when ptb_account_score_c > var1 then 1 else 0
end as Blah
from
salesforce_production.accounts, myconstant, myconstant2
你不需要values
:
WITH
myconstant1 as (select AVG(ptb_account_score_c) as val from salesforce_production.accounts),
myconstant2 as (select 6 as val)
SELECT Id, ptb_account_score_c, myconstant1.val,
myconstant2.val,
case when ptb_account_score_c > myconstant1.val then 1 else 0 end as Blah
FROM salesforce_production.accounts,myconstant1,myconstant2
我想你只是想要一个 window 函数:
select a.*,
(case when ptb_account_score_c > avg(a.ptb_account_score_c) over () then 1 else 0 end) as Blah
from salesforce_production.accounts a;
如果需要,您可以将这些组合成一个 CTE:
with params as (
select AVG(ptb_account_score_c) as var1, 6 as var2
from salesforce_production.accounts
)
select a.id, a.ptb_account_score_c,
params.var1, params.var2,
(case when a.ptb_account_score_c > params.var1 then 1 else 0 end) as Blah
from salesforce_production.accounts a cross join
params;