7

My understanding is that GREATEST() and LEAST() are not part of the SQL standard, but are very common.

I'm wondering, is there a way to clone the functionality of GREATEST keeping within the SQL standard?

SELECT id, GREATEST(1,2,3,4,5,6,7) AS number FROM table

The fully query:

  SELECT SUBSTR(section,1,2) AS campus, 
           AVG(GREATEST(maximum - enrolled, 0)) AS empty 
    FROM sectionrun 
   WHERE coursenumber = '105' AND subject = 'ENGL' 
GROUP BY campus
NullUserException
  • 81,190
  • 27
  • 202
  • 228
WalterJ89
  • 1,005
  • 2
  • 7
  • 24
  • 3
    For what database? GREATEST & LEAST are supported by [PostgreSQL](http://www.postgresql.org/docs/8.1/interactive/functions-conditional.html), [MySQL](http://dev.mysql.com/doc/refman/4.1/en/comparison-operators.html#function_greatest), [Oracle](http://techonthenet.com/oracle/functions/greatest.php). SQL Server is the only one of the majors that doesn't support GREATEST/LEAST. – OMG Ponies Sep 25 '10 at 17:58
  • 1
    I know that PostgreSQL and MySQL support GREATEST/LEAST. my question involves the actual SQL standard http://en.wikipedia.org/wiki/SQL#Standardization – WalterJ89 Sep 25 '10 at 22:35
  • See also: http://stackoverflow.com/questions/71022/sql-max-of-multiple-columns – Mark Byers May 23 '12 at 12:07

3 Answers3

5
GREATEST(1,2,3,4,5,6,7) AS number

can become

(select max(tmp) from (
        select 1 tmp from dual
        union all
        select 2 tmp from dual
        union all
        select 3 tmp from dual
        union all
        select 4 tmp from dual
        union all
        select 5 tmp from dual
        union all
        select 6 tmp from dual
        union all
        select 7 tmp from dual
) ) AS number          
Never Sleep Again
  • 1,211
  • 9
  • 10
4

You can use the CASE expression:

  SELECT SUBSTR(section,1,2) AS campus, 
           AVG(CASE WHEN maximum - enrolled > 0 
                    THEN maximum - enrolled
                    ELSE 0
               END) AS empty 
    FROM sectionrun 
   WHERE coursenumber = '105' AND subject = 'ENGL' 
GROUP BY campus
Aillyn
  • 22,334
  • 24
  • 56
  • 82
  • 4
    This won't scale very well to much more than two values. It's fine for the OPs specific example, but doesn't answer the more general question. – Mark Byers Apr 24 '12 at 08:49
2

As of now, GREATEST() and LEAST() are supported in Azure SQL. SQL Server 2022 will have it for on-premises installations.

GREATEST documentation:

https://docs.microsoft.com/en-us/sql/t-sql/functions/logical-functions-greatest-transact-sql?view=sql-server-ver15

Dave Markle
  • 92,195
  • 20
  • 143
  • 169