简体   繁体   中英

Get Least Value in a row

I have row of 12 months entry as follows and I would like to get least values of it. I have an idea to implement with CASE expression but which looks too complex in readability.

Table

   +----------------------------------------------------------------------------+
   | Id | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
   +----------------------------------------------------------------------------+
   | 1  | 0.1 | 1   | -2  | -0.5|  3  |  5  |  9  | 1.5 | 2.5 | 3.6 | 3.6 | 2.5 |
   | 2  | 3   | 2   | 5   | 2.5 |  3  |  6  |  10 | 1.1 | 2.8 | 2.6 | 5.6 | 1.8 |
   | 3  | -1  | 1   | 3   | -0.5|  3  |  5  |  9  | 1.5 | 2.5 | 3.6 | 3.6 | 2.5 |
   +----------------------------------------------------------------------------+

Expected Output

   +------------------------------------------------------------------------------------+
   | Id | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec | Least |
   +------------------------------------------------------------------------------------+
   | 1  | 0.1 | 1   | -2  | -0.5|  3  |  5  |  9  | 1.5 | 2.5 | 3.6 | 3.6 | 2.5 | -2    |
   | 2  | 3   | 2   | 5   | 2.5 |  3  |  6  |  10 | 1.1 | 2.8 | 2.6 | 5.6 | 1.8 | 1.1   |
   | 3  | -1  | 1   | 3   | -0.5|  3  |  5  |  9  | 1.5 | 2.5 | 3.6 | 3.6 | 2.5 | -1    |
   +------------------------------------------------------------------------------------+

I have tried a query like below but which is too complex in readability - is there any way to do it more effectively?

SELECT Id, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec,
       CASE WHEN Jan< Feb && Jan < Mar && Jan < Apr && Jan < MAY && Jan < Jun && Jan < Jul && Jan < Aug && Jan < Sep && Jan < Oct && Jan < Nov && Jan < Dec THEN Jan
            WHEN Feb < Jan && Feb < Mar && Feb < Apr && Feb < MAY && Feb < Jun && Feb < Jul && Feb < Aug && Feb < Sep && Feb < Oct && Feb < Nov && Feb < Dec THEN Feb
            WHEN...
       END AS Least     
FROM table

You may try cross apply . See below script:

SELECT Id, Jan, Feb, Mar, Apr, May, Jun, Jul ,Aug, Sep, Oct, Nov, Dec, Least
FROM Test
CROSS APPLY (SELECT MIN(MinColVal) AS Least FROM (VALUES (Jan),(Feb),(Mar),(Apr),(May),(Jun),(Jul),(Aug),(Sep),(Oct),(Nov),(Dec)) AS a(MinColVal))tab

This should do the trick.

SELECT ID, MIN(MONTH) AS Least
FROM
(
    SELECT JAN AS MONTH
    FROM ##table
    UNION ALL
    SELECT FEB AS MONTH
    FROM ##table
    UNION ALL
    SELECT MAR AS MONTH
    FROM ##table
) mon
GROUP BY ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM