Finding the lowest value in a table greater than a certain value

前端 未结 6 945
臣服心动
臣服心动 2021-02-09 14:01

Say I have the following data

Name      Value
===============
Small        10
Medium      100
Large      1000

Imagine that these represent the

6条回答
  •  难免孤独
    2021-02-09 14:10

    Just for fun I made the assumption that the target sizes are coming from a table of packages and you want to find the boxes for a bunch of packages. COALESCE chooses the second value if the first is NULL.

    SELECT  
        p.pkgid,  
        p.pkgsize,  
        COALESCE(MIN(b1.size), MAX(b2.size) AS boxsize    
    FROM packages AS p  
    LEFT JOIN boxes AS b1 ON p.pkgsize < b1.boxsize  
    LEFT JOIN boxes AS b2  -- yes, a cartesian join 
    GROUP BY p.pkgid, p.pkgsize
    

    As a single statement to compare to the other solutions, use

    SELECT  
        COALESCE(MIN(b1.size), MAX(b2.size) AS boxsize    
    FROM Table AS t1,  
         Table AS t2   
    WHERE targetsize < t1.Value
    

提交回复
热议问题