iLoctus
iLoctus

Reputation: 1

SQL'Where IF' statement

I'm currently trying to get a value from two tables. I have table A and Table B

Table A holds the main data of which i will be using to display my results.

Table B hold data which holds data if a certain condition in table A is met.

Table A

UserID   |Date        |useExternalInfo  |Address     |Hours
1        |12/12/2014  |0                |myaddress 1 | 4
2        |13/12/2014  |0               |myaddress 2 | 9 
3        | 14/12/2014 |1               | myaddress 3| 12

Table B

ID    | Date          |Hours
1     |  12/12/2014   |   10
2     |  13/12/2014   |   6
3     |  14/12/2014   |   7
3     |  15/12/2014   |   8

the query i'm trying to get is

select UserID, Date,  (hours from TableA if UseExternalinfo is 0, and from hours TableB if useextername) 
from TableA 
where 
TableA.Date = '14/12/2014' if (ExternalUse = 0) or TableB.Date = '14/12/2014' if (ExternalUse = 1)
and user = 3

for example if date is '14/12/2014' and user = 3 i need to find the hours of 7 not 12 because use external is 1.

Not sure if that makes sense i'm just basically trying to get a 'where if' statement if such a thing exists. Could someone point me in the right direction how i could achieve this please.

thanks

Upvotes: 0

Views: 43

Answers (1)

paul
paul

Reputation: 22021

select  UserID, 
        Date,  
        case when UseExternalInfo = 1 then tableA.hours else tableB.hours end 
from    TableA left join tableB on TableA.UserId = tableB.Id
where   TableA.Date = '14/12/2014' and
        TableB.Date = '14/12/2014' and
        user = 3

Upvotes: 1

Related Questions