Q
Problem solve Get help with specific problems with your technologies, process and projects.

MAX and COUNT DISTINCT

I have a table in which I do a SELECT DISTINCT on a date column. I am trying to write a query that returns only one value (MAX value) if there are more than one distinct dates in that column. What is the most efficient way of writing this SQL query?

Well, I'm not sure about the "most efficient" way, since efficiency in general depends on which database system you're using, whether there are indexes, and so on.

Your query would be something like this:

select case when ( select count(distinct datecol)
                     from yourtable )
               > 1
            then ( select max(datecol)
                     from yourtable )
            else null
        end 

Notice that if there are not more than 1 distinct values in datecol, the query returns NULL. You didn't say what you wanted in that situation.

This was last published in June 2005

Dig Deeper on Oracle and SQL

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide.com

SearchDataCenter

SearchContentManagement

SearchHRSoftware

Close