SQL标准中最好的和最少的

时间:2010-09-25 15:50:23

标签: sql standards

我的理解是GREATEST()和LEAST()不是SQL标准的一部分,但很常见。

我想知道,有没有办法克隆GREATEST的功能,保持在SQL标准内?

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

完全查询:

  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

3 个答案:

答案 0 :(得分:4)

您可以使用CASE表达式:

  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

答案 1 :(得分:2)

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

可以成为

(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          

答案 2 :(得分:0)

截至目前,Azure SQL 支持 GREATEST() 和 LEAST()。 SQL Server 2021(如果这就是它的名字)将用于本地安装。

最好的文档:

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