将查询的结果分配给变量以用于case语句

问题描述 投票:0回答:2

我正在尝试获取总样本列的平均值,并与每个特定记录的列值进行比较。

我已经在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
sql postgresql case analytics
2个回答
1
投票

我认为您只需要一个窗口函数:

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;

1
投票

您不需要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
© www.soinside.com 2019 - 2024. All rights reserved.