• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Count Distinct IDs in a date range given a start and end time

Resolved: Count Distinct IDs in a date range given a start and end time

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have a BigQuery table like this
id start_date end_date location type
1 2022-01-01 2022-01-01 MO mobile
1 2022-01-01 2022-01-02 MO mobile
2 2022-01-02 2022-01-03 AZ laptop
3 2022-01-03 2022-01-03 AZ mobile
3 2022-01-03 2022-01-03 AZ mobile
3 2022-01-03 2022-01-03 AZ mobile
2 2022-01-02 2022-01-03 CA laptop
4 2022-01-02 2022-01-03 CA mobile
5 2022-01-02 2022-01-03 CA laptop

I want to return the number of unique IDs by location and type of an arbitrary date range.
The issue I have is that there are multiple repeating lines covering similar dates, like the first two rows above.
For example, a date range of 2022-01-02 and 2022-01-03 would return
location type count distinct ID
AZ laptop 1
AZ mobile 1
CA laptop 2
CA mobile 1
MO mobile 1

I first tried creating a list of dates in like
and using ROW_NUMBER() OVER (PARTITION BY id,start_date,end_date) to expose only unique rows.
But I was only able to return the number of unique IDs for each day, rather than looking at the full date range as a whole.
I then tried joining to the same cte to return a unique row for each date, so something like
date | id | start_date | end_date | location | type
Where the columns from the first table above are duplicated for each date but this would require generating a huge number of rows to then further work with.
What is the correct way to acheive the desired result?

Answer:

I think the simplest way is
with output (if applied to sample data in your question)
enter image description here

If you have better answer, please add a comment about this, thank you!

google-bigquery sql
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Visual Studio 2022 crashes when using breakpoints

24/03/2023

Resolved: How to get Union type from an array of objects in Flow?

24/03/2023

Resolved: Modify entity using Action in C#

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.