How do I combine 2 select statements into one?

后端 未结 8 2211
执念已碎
执念已碎 2020-12-23 13:23

I am a noob when it comes to SQL syntax.

I have a table with lots of rows and columns of course :P Lets say it looks like this:

      AAA BBB CCC DD         


        
8条回答
  •  清酒与你
    2020-12-23 14:10

    Thanks for the input. Tried the stuff that has been mentioned here and these are the 2 I got to work:

    (
    select 'OK', * from WorkItems t1
    where exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
    AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
    AND TimeStamp>'2009-02-12 18:00:00'
    AND (BoolField05=1)
    )
    UNION
    (
    select 'DEL', * from WorkItems t1
    where exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
    AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
    AND TimeStamp>'2009-02-12 18:00:00'
    AND NOT (BoolField05=1)
    )
    

    AND

    select 
        case
            when
                (BoolField05=1)
        then 'OK'
        else 'DEL'
            end,
            *
    from WorkItems t1
    Where
                exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
                AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
                AND TimeStamp>'2009-02-12 18:00:00'
    

    Which would be the most efficient of these (edit: the second as it only scans the table once), and is it possible to make it even more efficient? (The BoolField=1) is really a variable (dyn sql) that can contain any where statement on the table.

    I am running on MS SQL 2005. Tried Quassnoi examples but did not work as expected.

提交回复
热议问题