【问题标题】:Getting two values with two different WHERE使用两个不同的 WHERE 获取两个值
【发布时间】:2020-08-07 07:05:31
【问题描述】:

所以我试图获得一个值,即来自一个州的名称的最大数量,然后是来自所有州的该名称的总数。 我想我必须做一个WHERE * IN,但不知道该放什么。这就是我目前所拥有的

SELECT name,SUM(number) as total
FROM
`bigquery-public-data.usa_names.usa_1910_current`
where state = 'AL'
group by name;

【问题讨论】:

  • 我试图做 WHERE name = ( max(number) from bigquery-public-data.usa_names.usa_1910_current where state = 'AL') 但当然这不起作用,因为它是一个字符串。
  • 结果会是什么样子?分享预期输出的例子

标签: sql group-by google-bigquery sum greatest-n-per-group


【解决方案1】:

考虑:

select name, sum(number) total
from bigquery-public-data.usa_names.usa_1910_current t
where name = (
    select name
    from bigquery-public-data.usa_names.usa_1910_current
    where state = 'AL'
    order by number desc
    limit 1
)
group by name

子查询恢复状态 AL 中具有最大 numbername。然后,外部查询计算整个数据集中该名称的总和 number

【讨论】:

  • 哦,好的,我明白我在“where name =”部分搞砸了,谢谢!
【解决方案2】:

以下是 BigQuery 标准 SQL

#standardSQL
SELECT name, 
  SUM(IF(state = 'AL', number, 0)) count_in_AL,
  SUM(number) total_count
FROM `bigquery-public-data.usa_names.usa_1910_current`
GROUP BY name
ORDER BY count_in_AL DESC 
LIMIT 1 

结果

Row name    count_in_AL total_count  
1   James   158827      5015584  

这意味着:詹姆斯是 AL 中最受欢迎的名字(有 158,827 个),所有州的总数为 5,015,584 个

【讨论】:

    猜你喜欢
    • 2013-10-03
    • 1970-01-01
    • 2023-03-31
    • 2016-09-03
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2020-01-10
    • 2021-06-21
    相关资源
    最近更新 更多