Okay, so these are my three tables:
USER
|--------+----------+----------|
| UserID | UserName | IsActive |
|--------+----------+----------|
| 10 | Mike | 1 |
| 11 | John | 1 |
| 12 | Beth | 1 |
|--------+----------+----------|
REPORT_DISTRIB (Linking Table)
|-----------+--------+----------+---------------|
| DistribID | UserID | ReportID | DistribToUser |
|-----------+--------+----------+---------------|
| 1 | 10 | 50 | 1 |
| 2 | 12 | 52 | 0 |
| 3 | 14 | 54 | 1 |
|-----------+--------+----------+---------------|
REPORT
|----------+------------+---------------|
| ReportID | ReportName | Distributable |
|----------+------------+---------------|
| 50 | FY2010 | 1 |
| 51 | FY2011 | 1 |
| 52 | FY2012 | 1 |
|----------+------------+---------------|
In the problem I’m facing, I have 200 users from the USER table that are active and 10 reports from the REPORT table that are distributable. For every user I need to display the User Name, the Report Name, and whether that report should be distributed to the user, like so:
|----------+------------+---------------|
| UserName | ReportName | DistribToUser |
|----------+------------+---------------|
| Mike | FY2010 | 1 |
| Beth | FY2012 | 0 |
|----------+------------+---------------|
What I’m trying to achieve is a list of 2000 results (200 users x 10 reports). The problem is that the REPORT_DISTRIB linking table doesn’t have a record for every user with each report. I still feel like this should be possible… am I wrong in my thinking? Any help is greatly appreciated.
It’s rough, but this is my query so far (which returns 1790 results):
SELECT u.UserName, r.ReportName, rd.DistribToUser
FROM USER u
LEFT JOIN REPORT_DISTRIB rd on rd.UserID = u.UserID
and rd.ReportID in (select r.ReportID from REPORT r where r.Distributable = 1)
OUTER APPLY (select r.ReportName from REPORT r where r.ReportID = rd.ReportID) r
WHERE u.IsActive = 1
1 Answer