簡體   English   中英

合並 SQL 中兩個不同查詢的結果集

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

我有 2 個包含飲料數據的表。 一張表有關於售出多少飲料的信息,第二張表有新飲料的數據。

我想獲取有關日期的數據,希望如下所示。 這兩個表都有兩個共同的“日期”和“飲料”列。
每天都會出售飲料並添加新的飲料。 我正在使用交叉連接來組合這兩個表中的數據,復雜的部分是如果任何表在特定日期銷售或帶來的飲料數量為 0,我想顯示 0。
任何人都可以提供任何解決方案,以解決如何以下列樣式組合數據。 任何幫助將不勝感激。

在此處輸入圖像描述 在此處輸入圖像描述

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-無論如何,您的查詢都應該給您錯誤,因為在您的第二個查詢中沒有別名為“u”的表。 我們還需要一個聯合和聚合 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

您可以使用UNION ALL獲取 2 個表:

在這里查看更多:聯盟

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