![](/img/trans.png)
[英]How to return difference in string values from the same column by doing a grouped string comparison in bigquery sql?
[英]How to SUM values from 2 separate tables that share the same column name in SQL
我有 2 個表,它們的列完全相同,但數據不同。 列是“姓名”、“性別”和“計數”。 第一個表名為 names_2014,第二個表名為 names_2015。 我的目標只是在這兩個表中找到前 5 個最受歡迎的名字。
我知道要獲得一張桌子最受歡迎的名字是:
SELECT name, count
FROM names_2014
ORDER BY count DESC
LIMIT 5;
但是,我最接近目標的是:
SELECT name, count
FROM names_2014
UNION DISTINCT -- I've tried UNION ALL as well
SELECT name, SUM(count)
FROM names_2015
GROUP BY name
ORDER BY count DESC
LIMIT 5
我已經嘗試了許多類似的變體,但沒有一個是成功的。 似乎我需要合並兩個表,然后是 SUM(count) 和 GROUP BY 名稱,但我想我沒有正確合並表。 非常感謝任何幫助,因為我已經花了幾個小時在這上面,我覺得解決方案是如此接近,但我只是看不到它。 我是 SQL 的新手,只是想測試我的極限。
您可以對合並兩個表的子查詢執行聚合,如下所示:
select name, sum(count) cnt
from
(
select name, count
from names_2014
union all
select name, count
from names_2015
) T
group by name
order by cnt desc
limit 5
從您的最終詢問中,不清楚您是否要按源表將這些前 5 名分開。 以下是您可能正在尋找的一個答案:
with name_2014 as (
select 'a' as name, 'm' as gender, 1 as cnt
union all
select 'b' as name, 'f' as gender, 3 as cnt
union all
select 'c' as name, 'm' as gender, 2 as cnt
),
name_2015 as (
select 'd' as name, 'f' as gender, 10 as cnt
union all
select 'b' as name, 'f' as gender, 5 as cnt
union all
select 'e' as name, 'm' as gender, 1 as cnt
)
(select 'name_2014' as src_table_name, name, sum(cnt) as total_counts from name_2014 group by name order by 3 desc limit 1)
union all
(select 'name_2015' as src_table_name, name, sum(cnt) as total_counts from name_2015 group by name order by 3 desc limit 1)
此示例查詢將為您提供每個表的前 1 個名稱。 (您可以更改限制並從查詢中獲得前 5 名。)如果您不想知道表名,可以調整上述查詢。
如果您根本不關心源表而只想要前 5 名,那么:
with name_2014 as (
select 'a' as name, 'm' as gender, 1 as cnt
union all
select 'b' as name, 'f' as gender, 3 as cnt
union all
select 'c' as name, 'm' as gender, 2 as cnt
),
name_2015 as (
select 'd' as name, 'f' as gender, 10 as cnt
union all
select 'b' as name, 'f' as gender, 5 as cnt
union all
select 'e' as name, 'm' as gender, 1 as cnt
)
select name, sum(cnt) as total_count from
(select name, cnt from name_2014
union all
select name, cnt from name_2015)
group by 1 order by 2 desc limit 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.