General SQL question/assistance

  • Hey all.  Novice SQL guy here and need a little assistance with a query.  Here's a sample data set:

    CREATE TABLE #temp_dat1 (

    Id int null,

    Code nvarchar(50) null,

    CompletedDate datetime null)

    INSERT INTO #temp_dat1 VALUES (1, 'Other', '2020-01-02 17:14:52.000')

    INSERT INTO #temp_dat1 VALUES (1, 'Verified', '2020-01-02 16:36:09.000')

    INSERT INTO #temp_dat1 VALUES (1, 'Loaner', '2020-01-02 17:21:45.000')

    INSERT INTO #temp_dat1 VALUES (1, 'Not Found', '2020-01-02 17:21:49.000')

    INSERT INTO #temp_dat1 VALUES (1, 'Demo', '2020-01-02 19:03:52.000')

    select Id, MAX(CompletedDate) from #temp_dat1 GROUP BY Id

     

    So I wold get the following values from the select:

    1  2020-01-02 19:03:52.000

    What I want to do is not have a result returned if the Code "Not Found" is associated with the MAX(CompletedDate) value.  Data would look like this:

    CREATE TABLE #temp_dat1 (

    Id int null,

    Code nvarchar(50) null,

    CompletedDate datetime null)

    INSERT INTO #temp_dat1 VALUES (1, 'Other', '2020-01-02 17:14:52.000')

    INSERT INTO #temp_dat1 VALUES (1, 'Verified', '2020-01-02 16:36:09.000')

    INSERT INTO #temp_dat1 VALUES (1, 'Loaner', '2020-01-02 17:21:45.000')

    INSERT INTO #temp_dat1 VALUES (1, 'Demo', '2020-01-02 17:21:49.000')

    INSERT INTO #temp_dat1 VALUES (1, 'Not Found', '2020-01-02 19:03:52.000')

    select Id, MAX(CompletedDate) from #temp_dat1 GROUP BY Id

    What's the best way of excluding (1, 'Not Found', '2020-01-02 19:03:52.000') without selecting the Code column in the query.  A where clause for (Code != 'Not Found') only excludes that record and brings back the next MAX(CompletedDate).  I want the result to return nothing if 'Not Found' is the last record for that date and Id.

    Any help is appreciated!

     

  • select Id, CompletedDate, Code 
    from (
    select *, row_number() over(partition by id order by completeddate desc) AS row_num
    from #temp_dat1
    ) as query1
    where row_num = 1 and code <> 'Not Found'

    SQL DBA,SQL Server MVP(07, 08, 09) "Money can't buy you happiness." Maybe so, but it can make your unhappiness a LOT more comfortable!

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

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