How do I combine 2 select statements into one?

后端 未结 8 2188
执念已碎
执念已碎 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:19

    use a case into the select and use in the where close a OR

    something like this, I didn't tested it but it should work, I think...

    select case when CCC='D' then 'test1' else 'test2' end, *
    from table
    where (CCC='D' AND DDD='X') or (CCC<>'D' AND DDD='X')
    
    0 讨论(0)
  • 2020-12-23 14:20

    You have two choices here. The first is to have two result sets which will set 'Test1' or 'Test2' based on the condition in the WHERE clause, and then UNION them together:

    select 
        'Test1', * 
    from 
        TABLE 
    Where 
        CCC='D' AND DDD='X' AND exists(select ...)
    UNION
    select 
        'Test2', * 
    from 
        TABLE
    Where
        CCC<>'D' AND DDD='X' AND exists(select ...)
    

    This might be an issue, because you are going to effectively scan/seek on TABLE twice.

    The other solution would be to select from the table once, and set 'Test1' or 'Test2' based on the conditions in TABLE:

    select 
        case 
            when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1'
            when CCC<>'D' AND DDD='X' AND exists(select ...) then 'Test2'
        end,
        * 
    from 
        TABLE 
    Where 
        (CCC='D' AND DDD='X' AND exists(select ...)) or
        (CCC<>'D' AND DDD='X' AND exists(select ...))
    

    The catch here being that you will have to duplicate the filter conditions in the CASE statement and the WHERE statement.

    0 讨论(0)
提交回复
热议问题