简体   繁体   English

合并 SQL 中两个不同查询的结果集

[英]Merge result set of two different queries in SQL

I have 2 tables which have data of Drinks.我有 2 个包含饮料数据的表。 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.我正在使用交叉连接来组合这两个表中的数据,复杂的部分是如果任何表在特定日期销售或带来的饮料数量为 0,我想显示 0。
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. @Andrian-无论如何,您的查询都应该给您错误,因为在您的第二个查询中没有别名为“u”的表。 Also we need a union and aggregate function to get your desired output.我们还需要一个联合和聚合 function 来获得您想要的 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:您可以使用UNION ALL获取 2 个表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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