简体   繁体   中英

invalid use of group function error for extracting date with max and min

I'm trying to execute a query like this:

SELECT MAX(counter), MIN(counter) ,
       my_date IN (SELECT my_date FROM my_table WHERE counter = MAX(counter) )  AS max_Date ,
       my_date IN (SELECT my_date FROM my_table WHERE counter = MIN(counter) ) AS min_Date 
FROM my_table;

and it's giving me the "invalid use of group function" error. what I want to do is to find the date for the maximum counter and then find the date for the minimum counter. Any help!! really appreciate it .. thanks.

You're trying to use the result of aggregate functions (max()/min()) on a row-by-row basis, but those results are not available until the DB has scanned the entire table.

eg it's a chicken and egg problem. You need to count chickens, but the eggs that will produce the chickens haven't even been layed yet.

That's why there's HAVING clauses, which allow you to use the results of aggregate functions to do filtering.

Try this for the subqueries:

SELECT my_date FROM my_table HAVING counter = MIN(counter) 
                             ^^^^^^

You can get the dates where the largest and smallest counter values appear using a trick with group_concat() and substring_index() :

SELECT MAX(counter), MIN(counter) ,
       substring_index(group_concat(my_date order by counter desc), ',', 1) as max_date,
       substring_index(group_concat(my_date order by counter), ',', 1) as min_date
FROM my_table;

Note: You probably want to format the date first to your liking.

You can also do this with a join.

The problem with your query is:

where counter = min(counter)

You can't include aggregation functions in the where clause, because both are referring to the table in the subquery. You could possibly do this using aliaes, but why bother? There are other ways to write the query.

You need a subselect to get the max and min counters and then join back against the table a couple of times to get the other values from those rows.

SELECT MaxCounter, MinCounter, a.my_date, b.my_date
FROM (SELECT MAX(counter) AS MaxCounter, MIN(counter) AS MinCounter 
FROM my_table) Sub1
INNER JOIN my_table a ON Sub1.MaxCounter
INNER JOIN my_table b ON Sub1.MinCounter

Note that this does assume that counter is unique!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM