1

I am trying to take the avg of a total sample column and compare to the column value off each specific record.

I have done this in SQL Server by declaring a variable and then setting it to the results of a query.

I am trying to do the same thing in PG, but I am not having any success.

In the below sample, myconstant2 works because of the hard coded value but myconstant does not because the value is set to the single row query result.

Any pointers here?

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
1
  • 1
    Sample data and desired results would help. Commented Dec 17, 2019 at 18:07

2 Answers 2

1

I think you just want a window function:

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;

If you wanted, you could combine these into a single 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;
Sign up to request clarification or add additional context in comments.

1 Comment

the params CTE is what I was looking for. Guess I am a dummy and didnt realize the cross join would get me what I wanted. THANK YOU
1

You don't need 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

3 Comments

The second values is perfectly valid select 6 as var2 can indeed be written as values (6)
myconstant1.val and myconstant2.val are columns not tables. What are they doing in the FROM clause?
@a_horse_with_no_name my comment was about: FROM salesforce_production.accounts,myconstant1.val,myconstant2.val which was the code before it was edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.