views:

24

answers:

2

This is my sql query:

select case when table.field1 = 1 then 1
            when table.field2 = 3 then 3
            when table.field2 = 4 then 4
            when table.field3 = 1 then 5
            else .... Status //item name
from table

I want that in case the "else" occurs -> the row will be removed from the dataSet. I can't use "Status" in the where clause for some reason.

Ideas?

A: 

The most straitforward way is to set conditions for the fields from "when", I.e. field1=1 or field2 in (3,4) or field3=1

spbfox
Just imagine there are 20 cases in the "case". And they are longer than shown here. It will really make a mess out of the where clause and make it non-readable.
Faruz
I agree, this may become ugly, but your request means that you do want all those conditions in "where" clause. You cannot use the field generated by case in "where" part of the query. Is it possible that the whole approach is wrong? Could you provide more details about what you are trying to do?
spbfox
+2  A: 

You could use a common table expression:

with TempResult (id, status)
as
(
    select primary_key_column,
           case when table.field1 = 1 then 1
                when table.field2 = 3 then 3
                when table.field2 = 4 then 4
                when table.field3 = 1 then 5
                else 0
    from table
)

select id
from TempResult
where status > 0
I Like it. I'll wait before approving it as an answer because I hope there's a nicer solution. I hope to keep it all with 1 select.
Faruz