Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT(*) FILTER (WHERE... In BigQuery

How can I filter in a count in BigQuery?

In Postgres I was doing something like:

COUNT(*) FILTER (WHERE event_date>('{{ report_date }}'::date-INTERVAL '2 WEEK'))

Though this does not work in BigQuery. What't the best alternative? I use standard SQL.

like image 674
Marco Greselin Avatar asked Nov 19 '17 15:11

Marco Greselin


2 Answers

Use case:

SUM(CASE WHEN event_date > '{{ report_date }}'::date-INTERVAL '2 WEEK' THEN 1 ELSE 0 END)

This is the "old-fashioned" way, before Postgres implemented the ANSI standard FILTER syntax.

like image 114
Gordon Linoff Avatar answered Sep 21 '22 17:09

Gordon Linoff


For BigQuery Standard SQL, you can use COUNTIF and DATE_SUB functions as below

COUNTIF(event_date > DATE_SUB(CURRENT_DATE(), INTERVAL 2 WEEK))  

You can test / play with above using below dummy example

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 1 AS event_id, DATE '2017-11-19' AS event_date UNION ALL
  SELECT 2, DATE '2017-11-18' UNION ALL
  SELECT 3, DATE '2017-10-15' 
)
SELECT 
  COUNT(*) AS all_events,
  COUNTIF(event_date > DATE_SUB(CURRENT_DATE(), INTERVAL 2 WEEK)) AS qualified_events 
FROM `project.dataset.yourTable`   

The output as one would expect is

all_events  qualified_events     
3           2    
like image 35
Mikhail Berlyant Avatar answered Sep 20 '22 17:09

Mikhail Berlyant