我正在尝试获取总样本列的平均值,并与每个特定记录的列值进行比较。
我已经在SQL Server中通过声明变量,然后将其设置为查询结果来完成此操作。
我试图在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
我认为您只需要一个窗口函数:
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;
您不需要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