Tarvo Mäesepp
Tarvo Mäesepp

Reputation: 4533

SQL UNION query returns first row with column names

I am in a situation where I use UNION to combine my queries. But the problem is that the first row is duplicate of column names like so:

enter image description here

What I am doing wrong? If I do not decalre row names statically in my first part then I get different number of columns error. This is my query:

SELECT "id"
     , "place_id"
     , [...]
     , (SELECT Count(pl.payment_method = 'PREPAID_CREDIT' )) AS prepaid_transactions
     , [...]
UNION
SELECT ps.id AS id
     , p.id AS place_id
     , [...]

Any help is appreciated.

Upvotes: 0

Views: 1206

Answers (2)

Job Curtis
Job Curtis

Reputation: 175

If your first query has no values for the columns that you've declared as strings, you can use NULL there instead. e.g;

SELECT NULL AS id
     , NULL AS place_id
     , [...]
     , (SELECT Count(pl.payment_method = 'PREPAID_CREDIT' )) AS prepaid_transactions
     , [...]
UNION
SELECT ps.id AS id
     , p.id AS place_id
     , [...]

and so on. All you really need to worry about is that both sides of the UNION have the same number of columns (and that the data in each column matches up).

Upvotes: 1

slaakso
slaakso

Reputation: 9080

You are selecting strings:

SELECT "id", "place_id", "client_id",...

You should select the actual column values from whichever table the data comes from

SELECT ps.id, p.place_id, p.client_id,...

Upvotes: 1

Related Questions