Search code examples
sql-servergroupingwindow-functionspartition

SQL: New column (categories) based on criteria from other table


I'm trying to create a new table that will act as a page-level security filter on a Power BI report. I have two tables, doc_class and comp_class, which are routinely updated and do all the calculations I need. I simply need a new table that will assign page access based on an OwnerID's presence in the doc_class table.

Any OwnerID in the doc_class table needs access to two Power BI pages: Doctor and Doctor ROI ALL OwnerIDs in the comp_class table need access to a different set of two pages: Practice and Practice ROI. All OwnerIDs in doc_class are also in comp_class, if that makes any difference. Page levels needs to each have their own row, and that is the part that is tripping me up.

Here are example tables (IDs only--the other data does not matter in this use case):

doc_class:      
| OwnerID  |
| -------- |
| 2        |
| 3        |

comp_class:
| OwnerID |
| --------|
| 1       |
| 2       |
| 3       |
| 4       |

Expected result:

| OwnerID  | page         |
| -------- | ------------ |
| 1        | Practice     |
| 1        | Practice ROI |
| 2        | Doctor       |
| 2        | Doctor ROI   |
| 2        | Practice     |
| 2        | Practice ROI |
| 3        | Doctor       |
| 3        | Doctor ROI   |
| 3        | Practice     |
| 3        | Practice ROI |
| 4        | Practice     |
| 4        | Practice ROI |

Solution

  • SELECT cc.ownerID, 'Practice' page
      FROM comp_class cc
     WHERE NOT EXISTS
              (SELECT 1
                 FROM doc_class dc
                WHERE dc.ownerID = cc.ownerID)
    UNION ALL
    SELECT ownerID, 'Practice ROI' page
      FROM comp_class cc
     WHERE NOT EXISTS
              (SELECT 1
                 FROM doc_class dc
                WHERE dc.ownerID = cc.ownerID)
    UNION ALL
    SELECT dc.ownerID, 'Doctor' page
      FROM doc_class dc
     WHERE EXISTS
              (SELECT 1
                 FROM comp_class cc
                WHERE cc.ownerID = dc.ownerID)
    UNION ALL
    SELECT dc.ownerID, 'Doctor ROI' page
      FROM doc_class dc
     WHERE EXISTS
              (SELECT 1
                 FROM comp_class cc
                WHERE cc.ownerID = dc.ownerID)
    UNION ALL
    SELECT dc.ownerID, 'Practice' page
      FROM doc_class dc
     WHERE EXISTS
              (SELECT 1
                 FROM comp_class cc
                WHERE cc.ownerID = dc.ownerID)
    UNION ALL
    SELECT dc.ownerID, 'Practice ROI' page
      FROM doc_class dc
     WHERE EXISTS
              (SELECT 1
                 FROM comp_class cc
                WHERE cc.ownerID = dc.ownerID);
    

    enter image description here