Given a SQL database with the following tables
TABLE Branch
- branch_Id INT primary key
TABLE Department
- dept_Id INT primary key
- branch_Id INT
Table Branch_Desc
- branch_Id INT primary key
- branch_Desc VARCHAR
TABLE Department_Desc
- department_Id INT primary key
- department_Desc VARCHAR
Is it possible to return a list of values in the tables above that match the following requirements:
" List all branches departments, branch descriptions and department descriptions where at least one of the descriptions (branch or department) matches a desired value " ?
The trick here is that the query is supposed to return a ONLY a matching descriptions so if we have the following scenario:
Branch: 1, Desc: test
Branch: 2, Desc: another
Department: 1, Desc: another
Department: 1, Desc: something else
With the desired value being 'another' the query should return:
Branch: 2, Branch Desc: another, Department: 1, Dept Desc: another
Branch Desc: 'test' and Dept Desc 'something else' should not be returned, nor should be Branch 1.
Assuming that the table structure cannot be changed is it possible to write a SQL query that would return the correct results?
so far the closest I got was:
SELECT br.branch_id, bd.branch_desc, de.dept_id, dd.dept_desc
FROM branch br
LEFT JOIN branch_desc bd
ON bd.branch_id = br.branch_id
AND UPPER(br.branch_desc) = 'value'
JOIN department de
ON br.branch_id = de.branch_id
LEFT JOIN department_desc dd
ON de.dept_id = dd.dept_id
AND UPPER(dd.dept_desc) = 'value'
This returns the correct values if at least one department contains a description for 'value' however when no departments contain the desired description then no rows are returned (even if there is a branch descriptions that matches 'value')
At this point I think two separate queries are required to achieve the correct results in all four possible scenarios:
- Both Branch and Department contain descriptions that match 'value'
- Only Branch contains descriptions that match 'value'
- Only Department contains descriptions that match 'value'
- Neither Branch nor Department contain descriptions that match value
If this is possible (and I have a feeling that it must be) I would appreciate any guidance towards the right direction.
Thanks in advance!