首页 > 解决方案 > 计算多个字符串并将每个字符串的计数放入列

问题描述

我真的是 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

我希望你们能理解我的问题并能给我帮助。提前致谢。

在此处输入图像描述

在此处输入图像描述

标签: sqlgoogle-bigquery

解决方案


你没有为你的输出提供详细信息,但如果我理解正确,你想这样做:

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

推荐阅读