Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine results of two queries into a single dataset

I have two queries : Queries Simplified excluding Joins

Query 1 : select ProductName,NumberofProducts (in inventory) from Table1.....; Query 2 : select ProductName, NumberofProductssold from Table2......; 

I would like to know how I can get an output as :

ProductName NumberofProducts(in inventory)  ProductName NumberofProductsSold 

The relationships used for getting the outputs for each query are different. I need the output this way for my SSRS report .

(I tried the union statement but it doesnt work for the output I want to see. )

like image 279
CodeNinja Avatar asked Mar 05 '13 17:03

CodeNinja


People also ask

How do I combine two SQL queries in one result without a UNION?

You need to create two separate queries and join their result not JOIN their tables. Show activity on this post. JOIN and UNION are differents. In your query you have used a CROSS JOIN operation, because when you use a comma between two table you apply a CROSS JOIN.

What can you use to combine data from two or more tables into a single result set?

UNION – Use Unions and other set operators to combine rows from one or more queries into one result.

How can you combine and return the result set retrieved by two or more?

Set operators are used to combine the results of two (or more) SELECT statements. Valid set operators in Oracle 11g are UNION, UNION ALL, INTERSECT, and MINUS. When used with two SELECT statements, the UNION set operator returns the results of both queries.


2 Answers

Here is an example that does a union between two completely unrelated tables: the Student and the Products table. It generates an output that is 4 columns:

select         FirstName as Column1,         LastName as Column2,         email as Column3,         null as Column4     from         Student union select         ProductName as Column1,         QuantityPerUnit as Column2,         null as Column3,         UnitsInStock as Column4     from         Products 

Obviously you'll tweak this for your own environment...

like image 61
Gojira Avatar answered Oct 05 '22 20:10

Gojira


I think you are after something like this; (Using row_number() with CTE and performing a FULL OUTER JOIN )

Fiddle example

;with t1 as (   select col1,col2, row_number() over (order by col1) rn   from table1  ), t2 as (   select col3,col4, row_number() over (order by col3) rn   from table2 ) select col1,col2,col3,col4 from t1 full outer join t2 on t1.rn = t2.rn 

Tables and data :

create table table1 (col1 int, col2 int) create table table2 (col3 int, col4 int)  insert into table1 values (1,2),(3,4)  insert into table2 values (10,11),(30,40),(50,60) 

Results :

|   COL1 |   COL2 | COL3 | COL4 | --------------------------------- |      1 |      2 |   10 |   11 | |      3 |      4 |   30 |   40 | | (null) | (null) |   50 |   60 | 
like image 34
Kaf Avatar answered Oct 05 '22 21:10

Kaf