How to join these two selects of the same table in SQL server?

Asked

Viewed 786 times

0

Next, I need the amount per month of each customer who entered the year managed to do this, however I want q be shown in only 1 result. How do I join the two SELECTS? In order that it is added to the right side of the first result "Input Month Year" the fields "QTD" and "Output Month Year". See the image I sent.

Thank you in advance!

NOTE: Both are part of the same table are only in different columns.

NOTE: I tried to use UNION but UNION it just groups the results in 2 fields and deletes the field "Output" tried to do a subquery (unsuccessfully).

Resultado das SELECTS

  • I probably didn’t understand your explanation of the purpose of your query but perhaps a FULL OUTER JOIN of these two queries about the month/year field can provide the desired result.

  • 2

    Put the code to create your table to try to reproduce here. You don’t need all the data, just a part... And puts your SELECT in text form as well, not image.

1 answer

2


Good morning Fernando!

I thought here of two solutions that might perhaps help with your problem. In both cases you can create an ID column in each case presented. Once this is done, let’s go the solutions I thought to try to help:

1) Creating this ID column in both cases, check if both will have the same amount of rows. If they have the same amount, I believe an INNER JOIN will solve the problem;

2) But if you do not have the same amount I believe FULL OUTER JOIN can solve. But in this case, FULL OUTER JOIN should follow this structure:

SELECT <seus dados>
FROM TableA  A
FULL OUTER JOIN TableB  B
ON A.Key = B.Key
WHERE A.Key is NULL
OR B.Key is NULL

Obs: Keeping in mind that your key in both tables will be the respective ID created.

I hope I can help.

Hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.