从左关节表计算非空值

时间:2019-08-14 11:03:37

标签: mysql google-cloud-platform google-bigquery

直接从左联合表上的select语句(不使用where)计算非空值

count(*) as comments需要此选项以仅提供非空值的计数。另外,inner join也不是解决方案,因为它不包含count(distinct (t1.postId)) as no_of_content

中注释为零的内容。
select  t1.tagId as tagId, count(distinct (t1.postId)) as no_of_content, count(*) as comments
from  content_created as t1
left join comment_created as t2 
on t1.postId=t2.postId
where   
(   (t1.tagId = "S2036623" )
 or  (t1.tagId = "S97422" )
)
group BY 1

2 个答案:

答案 0 :(得分:0)

尽管发布示例数据可能会帮助我们更多地回答此问题,但是您可以将计数功能更新为-

COUNT(CASE WHEN postId IS NULL THEN 1 END) as comments

答案 1 :(得分:0)

Count只计算非空值。您需要做的是显式引用右侧表的列。因此,不要说count(*),而要使用count(right_joined_table.join_key)。 这是使用BigQuery的完整示例:

with left_table as (
select num
from unnest(generate_array(1,10)) as num
), right_table as (
select num
from unnest(generate_array(2,10,2)) as num
)

select
  count(*) as total_rows,
  count(l.num) as left_table_counts,
  count(r.num) as non_null_counts
from left_table as l
left outer join right_table as r
on l.num = r.num

这将为您提供以下结果:

enter image description here