开发者

GREATEST and LEAST in SQL standard

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开发者_如何学Python 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


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          


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


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

GREATEST documentation:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜