Find lowest populated field, not min value

  • Hi all,

    I have a tricky one.

    I have a dataset as below which deals with airport delays.

    CREATE TABLE #delaystats

    (

    airport VARCHAR(10)

    ,thedate SMALLDATETIME

    ,delay1 INT

    ,delay2 INT

    ,delay3 INT

    ,delay4 INT

    ,delay5 INT

    )

    INSERT INTO #delaystats (airport,thedate,delay1,delay2,delay3,delay4,delay5)

    SELECT 'LAX', '01-May-2013',2,0,1,4,1 UNION ALL

    SELECT 'LAX', '02-May-2013',0,0,1,2,0 UNION ALL

    SELECT 'LAX', '03-May-2013',0,0,0,2,0

    SELECT * FROM #delaystats

    DROP TABLE #delaystats

    The dataset is quite simple and contains an airport code, date and field-names which represent flight delays. So delay1 contains a number representing how many flights where delays by 1 hour on that day, delay2 is 2 hours and so on.

    What I need to do is for each date return the field that represents the minimum delay for that day. Note it is not how many flights where delayed but the minimum delay for that day.

    So the result on the above dataset would be

    Airport Date MinDelay

    LAX 01-May-2013 Delay1

    LAX 02-May-2013 Delay3

    LAX 03-May-2013 Delay4

    Any ideas on how to achieve this?

    thanks,

    derrysql

  • How about:

    select airport,

    thedate,

    case when delay1 <> 0 then 'delay1'

    when delay2 <> 0 then 'delay2'

    when delay3 <> 0 then 'delay3'

    when delay4 <> 0 then 'delay4'

    when delay5 <> 0 then 'delay5'

    else 'no delays'

    end as 'Min Delay'

    from #delaystats


    And then again, I might be wrong ...
    David Webb

  • I agree with David here, since it's a relatively simple paradigm and a direct order of evaluation you've got. Anything more complex would be overkill, as well as non optimal, since CASE can short circuit the evaluation once it's true.


    - Craig Farrell

    Never stop learning, even if it hurts. Ego bruises are practically mandatory as you learn unless you've never risked enough to make a mistake.

    For better assistance in answering your questions[/url] | Forum Netiquette
    For index/tuning help, follow these directions.[/url] |Tally Tables[/url]

    Twitter: @AnyWayDBA

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply