ERROR: missing FROM-clause entry for table "p"

Viewed 1722

I am trying to use a UNION to append the total column in the first top half to the second half of the query.

SELECT NULL as month, NULL as active, count(cage_player_id) as total
FROM player_signup as p 
GROUP BY date_part('month', p.signup_date)

UNION 

SELECT date_part('month', signup_date) as month, count(DISTINCT(p.cage_player_id)) as active, NULL as total
FROM player_signup as p
JOIN daily_kpis as d ON p.cage_player_id = d.cage_player_id
WHERE slot_bet_amount > 0
OR ld_bet_amount > 0 
OR table_bet_amount > 0 
GROUP BY date_part('month', p.signup_date)
ORDER BY date_part('month', p.signup_date) ASC

I keep getting an error that says the FROM clause is missing for table p. Can anyone help? Is there an easier way to combine these two queries?

Here is what each query looks like separately. I just want to add the total column right next to the month and active column. The total ID's would still be broken down by months.

Query 1

Results

Query 2

Results

2 Answers

The problem is the order by clause. It applies to the results of the union query, so it cannot see the identifiers that are defined within the queries. Instead, you should use the names of the column in the resultset.

So you want to change this:

ORDER BY date_part('month', p.signup_date) ASC

To:

ORDER BY month

I believe this is the query you need:

SELECT date_part('month', signup_date) as month
       , count(DISTINCT(p.cage_player_id)) as active
       , (select count(cage_player_id) 
          FROM player_signup as p 
          GROUP BY date_part('month', p.signup_date)) as total
FROM player_signup as p
JOIN daily_kpis as d ON p.cage_player_id = d.cage_player_id
WHERE slot_bet_amount > 0
OR ld_bet_amount > 0 
OR table_bet_amount > 0 
GROUP BY date_part('month', p.signup_date)
ORDER BY date_part('month', p.signup_date) asc

I am not so good at Postgresql, please try this:

SELECT date_part('month', signup_date) as month
       , count(DISTINCT(p.cage_player_id)) as active
       , max(t1.total) as total
FROM player_signup as p
left join (select count(pp.cage_player_id) over (partition by date_part('month', pp.signup_date)) as total
                  , date_part('month', pp.signup_date) date_p
           FROM player_signup as pp) t1 on t1.date_p = date_part('month', p.signup_date)
JOIN daily_kpis as d ON p.cage_player_id = d.cage_player_id
WHERE slot_bet_amount > 0
OR ld_bet_amount > 0 
OR table_bet_amount > 0 
GROUP BY date_part('month', p.signup_date)
ORDER BY date_part('month', p.signup_date)
Related