Question

I use the Google Sheets SQL-ish Query function to summarize data in a number of my spreadsheets. This has been working well for years, albeit slowly.

Today, I'm having problems with some of my queries - specifically with some that compare dates in the source data to TODAY().

To demonstrate, here's a link to a shared spreadsheet that I've used to reproduce the problem on fake data.

Edit: Example has been updated with AdamL's suggestion.

enter image description here

The source data is in range A1:D6, with columns "Serial No.", "Type", "Location", and "Warranty Expiration". The last column is a date.

This function in A9 summarizes all data:

=query(A1:D6,"select B, count(A) group by B pivot C")

...like so:

=query(A1:D6,"select B, count(A) group by B pivot C")

Here's the thing. If I try to filter using WHERE and DATE(), the Query seems to break down completely. What I want is a table that looks like the one above, but including only data rows that have a date in column D that is in the past.

=query(A1:D6,"select B, count(A) where D < now() group by B pivot C")

=query(A1:D6,"select B, count(A) where D < now() group by B pivot C")

If I change the filter to something not involving dates, I get the expected output:

=query(A1:D6,"select B, count(A) where B='Mech' group by B pivot C")

How do I get this to give me the summary I want?

Was it helpful?

Solution

The now() scalar function returns a datetime value, and you have date values in the source data. Comparisons between the two will unfortunately fail. The workaround is to convert now() to a date value:

=QUERY(A1:D6;"select B, count(A) where D < toDate(now()) group by B pivot C")


As an aside, there is a limitation (bug?) with the QUERY function whereby the now() scalar function does not (necessarily) operate in the time zone of your spreadsheet, and there doesn't appear to be any way of modifying this behaviour. I believe that the now() scalar function will always return the current time in Pacific Daylight Time (eg US west coast). So for me, right now in Brisbane, Australia, toDate(now()) used in a QUERY select clause returns yesterday's date.

The safer bet is to use a spreadsheet function to generate today's date, and concatenate that into the QUERY clause:

=QUERY(A1:D6;"select B, count(A) where D < date '"&TEXT(GoogleClock();"yyyy-MM-dd")&"' group by B pivot C")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top