I have a few tables:
- “DCDetails” table which contains the Master data for a few diagnostics centers.
- “CompanyDetails” table which contains the Master data for Companies
- “Investigation” table which contains the Investigations(meaning set of medical tests to be conducted)
These are my master tables.
I also have a few mapping tables:
1. “CompanyDCMap” table which contains the MAPPING of Company to Diagnostic centers
2. “InvestigationDCMap” table which contains the MAPPING of Investigation to Diagnostic centers(Or DC for short)
I have to filter a set of DC based on two criteria which are:
- the DC belongs in the “CompanyDCMap” and
- Out of the DC filtered in (1), it also belongs in the “InvestigationDCMap” table.
How do I write the query for this so that I get the DC which are in both CompanyDCMap and InvestigationDCMap given I have the primary keys of “CompanyDetails” and “Investigation” tables.
I have almost given up, I am unable to think of a query which filters two sets at the same time.
Kindly help me.
UPDATE
Schema:
CompanyDetails table:
CompanyID(PRIMARY KEY), CompanyName(NVARCHAR(100))
1 Company1
2 Company2
3 Company3
Investigation Table:
InvestigationID(Primary key) , InvestigationName(NVARCHAR(100))
1 HIV+ Blood Test
2 TMT
3 Urine Test
DCDetails Table:
DCID(PRIMARY KEY), DCName(NVARCHAR(100))
1 DC1
2 DC2
3 DC3
CompanyDCMap table
CompanyDCMapID(Primary key), CompanyID(Foreign key), DCId(Foreign Key)
1 1 1
2 1 2
3 2 2
4 2 3
5 3 1
6 3 3
InvestigationDCMap table
InvestigationDCMapID(Primary Key), InvestigationID(Foreign Key), DCId(Foreign Key)
1 1 1
2 1 3
3 2 2
4 2 3
Expected Output of a query given CompanyID = 1 and InvestigationID = 2, SELECT DCId and DCName =
DCId(Int) DCName(NVARCHAR(100))
2 DC2
To get “distinct” values, you can use:
Or…
Better yet, since no relationships with the other tables are needed:
This will be a much more efficient query, but if you need other columns from the other tables, you’ll need to revert to the join version.