sql - 计算多个字符串并将每个字符串的计数放入列
问题描述
我真的是 sql 和 bigquery 的新手。在这种情况下,我使用bigquery-public-data.san_francisco_bikeshare.bikeshare_trips
数据集(图 1 和图 2)。
我想计算订阅者类型、“订阅者”和“客户”的总数,以及它们的平均持续时间_秒。
所以我想让它包含的列包括:
start_station name | total_Subscriber | total_nonSubscriber | avg_duration_Subscriber | avg_duration_nonSubscriber
我希望你们能理解我的问题并能给我帮助。提前致谢。
解决方案
你没有为你的输出提供详细信息,但如果我理解正确,你想这样做:
select count(*) totalCount
,count(case when subscriber_type ='Customer' then 1 end) CustomerCount
,count(case when subscriber_type ='Subscriber' then 1 end) subscriberCount
,avg(case when subscriber_type ='Customer' then durationsec end) CustomerAvg
,avg(case when subscriber_type ='Subscriber' then durationsec end) SubscriberAvg
from tablename
但是如果你想要每个起始站的计数和平均值,那么你需要按 start_station 分组:
select start_station
,count(*) totalCount
,count(case when subscriber_type ='Customer' then 1 end) CustomerCount
,count(case when subscriber_type ='Subscriber' then 1 end) subscriberCount
,avg(case when subscriber_type ='Customer' then durationsec end) CustomerAvg
,avg(case when subscriber_type ='Subscriber' then durationsec end) SubscriberAvg
from tablename
group by start_station
推荐阅读
- c - 使用指定的初始化程序使用 `char []` 成员初始化嵌套结构
- flutter - 从 Swagger-codegen 生成 DART 包
- java - 从 OAuth2.0 访问用户电子邮件?
- r - 如何隔离R中字符串中的某些字母?
- javascript - 正则表达式在大括号之间获取值,包括带有拆分的大括号
- python - 用 pandas 和 logy 绘图
- postgresql - Postgres 填补了缺失的主键
- postgresql - 如何用单引号插入 postgresql 数据 - 再问一遍
- python - 如果未安装可选模块,则测试代码行为
- ios - 从 NSURLSessionDataTask 呈现时,UIAlertController 会导致应用程序崩溃?