SQL - Display Multiple rows in one single row

Started on the old forum in February 2011 · view the original in the archive · old links redirect here

5 replies · 2,713 views · started 15 years ago · 1 min read

3 participants
PAUL41 Newbie · 5 posts #1

I have a query which will always display amounts on 2 seperate rows. Which i would like to merge together into 1 row. The complication of this is that 1 of the queries may return nothing.

SELECT amount FROM TABLE a WHERE REFERENCE IN(1,2)

RETURNS 2 rows. I need the above to display my answer as 1 row;

amount (ref1), amount (ref2).

The following does combine and give me what i want. However, if one of the queries does NOT return anything from the database then nothing is returned. I need it always to return something. (There will always be 1 query that will return something).

What i have so far which is not quite right;

SELECT * FROM( SELECT amount FROM Table a WHERE REFERENCE = 1) A (SELECT amount FORM Table b WHERE REFERENCE = 2)B

This does return what i need. However, if i amend the query for one of the select statements to say reference 3 which does not exist. Nothing is returned. I would still want reference 1 returned and null for the second query.

Requre outputs;

1, 1 1, null null, 1

null, null will never occur.

Any help would be appreciated.

Thanks in advance

frostymarvelous Senior · 266 posts #2

I'm not quite good with multiple queries as I never needed them, but have you tried using a union?

Perfection comes at a cost

I accept liberty!

PAUL41 Newbie · 5 posts #3

Hi thanks a union on the query I want sounds like it should work. However, I can't quite get the syntax correct. Anyone help?

frostymarvelous Senior · 266 posts #4

Just use UNION in between the two statements

Select 1 condition 1 UNION select 2 condition 2

Added after 2 minutes:

If it works right, you will have both result sets even if condition two returns no rows.

Perfection comes at a cost

I accept liberty!

GumSlone Administrator Principal · 1,690 posts #5

Here is an example for union all which ive used at one of my sites

(SELECT buddies.buddy2 AS buddy FROM buddies WHERE buddies.buddy1='1')
          UNION ALL (SELECT buddies.buddy1 AS buddy FROM buddies WHERE buddies.buddy2='1')
          ORDER BY lastactive DESC LIMIT 1,10

Advertise your mobile site for FREE with AdTwirl

External image (may be gone)

PAUL41 Newbie · 5 posts #6

Hi thanks for the replies. The union query does half the solution. As soon as I do a union I am back to displaying my results in 2 separate rows when I require them to always be returned in 1 row.

Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close