简体   繁体   中英

Merge result set of two different queries in SQL

I have 2 tables which have data of Drinks. One table has information about how many drinks were sold and the second table has data of the new drinks brought.

I want to fetch this data with respect to date want to show it like below. Both the tables have two common columns of 'Date' and 'Drink'.
On daily basis drinks are sold and new ones are added. I am using a cross join for combining the data from these two tables, and the complicated part is I want to show 0 if any table has 0 number of drinks sold or brought on a particular date.
Could anyone please provide any solution for how to combine the data in following style. Any help would be highly appreciated.

在此处输入图像描述 在此处输入图像描述

select *  from 
(  
   select Date(sellingDate) as 'Date', softDrink as 'Drinks',  Count(*)  as 'Sold'
   from sell where Date(sellingDate)= '1-1-2020' 
   group by Date(sellingDate), softDrink
) A

cross join 
(
   select Date(u.createdDate) as 'Date',softDrink as 'Drinks',  Count(*)  as 'Brought'
   from new_drinks as n
   inner join category as c on n.erID = c.erID
   where Date(c.createdDate)='1-1-2020' 
   group by Date(c.CreatedDate), n.softDrink
) B 

@Andrian - You query should give you error anyways as there is no table aliased as "u" in your second query. Also we need a union and aggregate function to get your desired output.

SELECT Date, Drinks, SUM(Sold) AS Sold, SUM(Brought) AS Brought
FROM
(SELECT Date(sellingDate) AS 'Date', softDrink AS 'Drinks',  Count(*)  AS 'Sold', 0 AS 'Brought'
FROM sell s
WHERE Date(s.sellingDate)= '1-1-2020' 
GROUP BY  Date(sellingDate), softDrink
UNION 
SELECT Date(c.createdDate) AS 'Date',softDrink AS 'Drinks', 0 AS 'Sold' , Count(*)  AS 'Brought'
FROM new_drinks AS n
INNER JOIN category AS c on n.erID = c.erID
WHERE Date(c.createdDate)='1-1-2020' 
GROUP BY Date(c.CreatedDate), n.softDrink
) A
GROUP BY Date, Drinks

You can use UNION ALL to fetch 2 tables:

See more here: Union

select * from (

select Date(sellingDate) as 'Date', softDrink as 'Drinks',  Count(*)  as 'Sold'
from sell where Date(sellingDate)= '1-1-2020' 

UNION ALL

select Date(u.createdDate) as 'Date',softDrink as 'Drinks',  Count(*)  as 'Brought'
from new_drinks as n
inner join category as c on n.erID = c.erID
where Date(c.createdDate)='1-1-2020' 
)
group by date, drinks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM