mardi 1 novembre 2016

SQL - Should I add an IF or CASE to this WHERE clause?

I've written a query that looks like this:

SELECT
xx.DATE
xx.TRANSACTION_ID
xx.ID
xx.CODE

FROM TABLE_X xx

WHERE
xx.DATE >= TO_DATE('2015-01-01', 'YYYY-MM-DD')
AND xx.ID IN 
(SELECT
yy.id
FROM TABLE_Y yy
WHERE
yy.status = 'OPEN'
AND yy.type = 1
AND trunc(yy.date) = TO_DATE('{FREE_FORM}', 'YYYY-MM-DD')
)

ex.TABLE_X

DATE        TRANSACTION_ID  ID      CODE
1/1/2015    1020            CAT     RED
1/1/2015    1010            CAT     GREEN
1/2/2015    2020            DOG     RED
1/2/2015    2010            DOG     GREEN
1/3/2015    3030            RABBIT  BLUE
1/3/2015    3020            SPIDER  RED
1/3/2015    3010            RABBIT  GREEN
1/4/2015    4020            CAT     RED
1/4/2015    4010            SNAKE   GREEN
1/4/2015    4000            MONKEY  ORANGE
1/5/2015    5020            HORSE   RED
1/5/2015    5010            COW     GREEN

ex.TABLE_Y

date        id      status  type
1/1/2015    CAT     OPEN    1
1/2/2015    DOG     OPEN    1
1/3/2015    RABBIT  OPEN    1

With these example tables my current output is:

ex.output

DATE        TRANSACTION_ID  ID      CODE
1/1/2015    1020            CAT     RED
1/1/2015    1010            CAT     GREEN
1/2/2015    2020            DOG     RED
1/2/2015    2010            DOG     GREEN
1/3/2015    3030            RABBIT  BLUE
1/3/2015    3010            RABBIT  GREEN
1/4/2015    4020            CAT     RED

I'd like to add something to maybe the WHERE clause like:

if (ex.output.CODE = RED){
SELECT
xx.DATE
xx.TRANSACTION_ID
xx.ID
xx.CODE

FROM TABLE_X xx

WHERE xx.TRANSACTION_ID = ex.output.TRANSACTION_ID - 10
}
AND
if (ex.output.CODE = GREEN){
SELECT
xx.DATE
xx.TRANSACTION_ID
xx.ID
xx.CODE

FROM TABLE_X xx

WHERE xx.TRANSACTION_ID = ex.output.TRANSACTION_ID + 10
}

My goal is to end up with an output of:

DATE        TRANSACTION_ID  ID      CODE
1/1/2015    1020            CAT     RED
1/1/2015    1010            CAT     GREEN
1/2/2015    2020            DOG     RED
1/2/2015    2010            DOG     GREEN
1/3/2015    3030            RABBIT  BLUE
1/3/2015    3020            SPIDER  RED
1/3/2015    3010            RABBIT  GREEN
1/4/2015    4020            CAT     RED
1/4/2015    4010            SNAKE   GREEN

Is this possible?

Aucun commentaire:

Enregistrer un commentaire