Mysql

為聚合連接多個表

  • August 4, 2019

如何使用 Sum 和 Count 函式連接多個表以進行聚合?

我正在嘗試的查詢如下:

Select
 campaigns.id,
 campaigns.name,
 Count(landers.campaign_id) As landers_count,
 Sum(conversions.revenue) As total_revenue
From
 campaigns Left Join
 conversions
   On campaigns.id = conversions.campaign_id Left Join
 landers
   On campaigns.id = landers.campaign_id
Group By
 campaigns.id

我什至嘗試過外部連接,但沒有運氣,我得到的結果不准確。

我的範例表如下:

廣告系列表:

| id | name           |
+----+----------------+
| 1  | Facebook Ads   |
| 2  | Bing Ads       |
| 3  | Direct Mailing |
| 4  | Solo Ads       |

蘭德斯表:

| id | name        | campaign_id |
+----+-------------+-------------+
| 1  | Lander 1    | 1           |
| 2  | Lander Two  | 2           |
| 3  | Lander 3    | 4           |
| 4  | Lander Four | 1           |

換算表:

| id | revenue | campaign_id | lander_id |
+----+---------+-------------+-----------+
| 1  | 25.00   | 1           | 1         |
| 2  | 12.00   | 1           | 4         |
| 3  | 19.00   | 4           | 3         |

我期待的結果應該如下所示:

| campaigns.id | campaigns.name | landers_count | total_revenue |
+--------------+----------------+---------------+---------------+
| 1            | Facebook Ads   | 2             | 37.00         |
| 2            | Bing Ads       | 1             | 00.00         |
| 3            | Direct Mailing | 0             | 00.00         |
| 4            | Solo Ads       | 1             | 19.00         |

小提琴基於@‘Willem Renzema’ 的回答

小提琴

此答案不正確,但我無法刪除已接受的答案。

相反,請參閱此問題的其他答案以獲取解決方案。

這個請求很老了,但由於接受的答案是錯誤的,我想我會添加一個正確的,所以未來的讀者不會太困惑。

一個campain有著陸器和轉換。如果我們僅僅連接所有表,我們會得到一個包含兩個著陸器和三個轉換 2 x 3 = 6 個結果行的廣告系列。如果我們然後求和或計數,我們會得到錯誤的結果(在範例中著陸器的數量將是三倍,轉換總和將加倍)。

主要有兩種方法可以解決這個問題:

在 select 子句中的子查詢中聚合。

select
 id, name,
 (select count(*) from landers l where l.campaign_id = ca.id) as landers_count,
 (select sum(revenue) from conversions co where co.campaign_id = ca.id) as total_revenue
from campaigns ca
order by id;

加入前聚合。

select ca.id, ca.name, l.landers_count, co.total_revenue
from campaigns ca
left join
(
 select campaign_id, count(*) as landers_count
 from landers
 group by campaign_id
) l on l.campaign_id = ca.id
left join
(
 select campaign_id, sum(revenue) as total_revenue
 from conversions
 group by campaign_id
) co on co.campaign_id = ca.id
order by ca.id;

您可以使用COALESCE在結果中獲取零而不是空值。

引用自:https://dba.stackexchange.com/questions/175786