SQL:基于其他表的条件的新列(类别)

问题描述 投票:0回答:2

我正在尝试创建一个新表,该表将充当 Power BI 报告的页面级安全过滤器。我有两个表,doc_class 和 comp_class,它们会定期更新并进行我需要的所有计算。我只需要一个新表,它将根据 OwnerID 在 doc_class 表中的存在分配页面访问权限。

doc_class 表中的任何 OwnerID 都需要访问两个 Power BI 页面:Doctor 和 Doctor ROI ALL comp_class 表中的所有者 ID 需要访问一组不同的两个页面:练习和练习 ROI。 doc_class 中的所有 OwnerID 也都在 comp_class 中,如果有区别的话。 页面级别需要每个都有自己的行,这就是让我绊倒的部分。

以下是示例表(仅 ID——在此用例中其他数据无关紧要):

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

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

预期结果:

| 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 |
sql-server grouping window-functions partition
2个回答
0
投票
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);


0
投票

替代解决方案。

Union
删除重复项,以便您可以利用它。还使用
cross apply
使代码更易于阅读。

-- Any OwnerID in the doc_class table needs access to two Power BI pages: Doctor and Doctor ROI
select OwnerID, [Page] 
from doc_class
    cross apply (
        select 'Doctor' [Page] union all
        select 'Doctor ROI' [Page]
    ) p

UNION

-- ALL OwnerIDs in the comp_class table need access to a different set of two pages: Practice and Practice ROI.
select OwnerID, [Page]  
from comp_class
    cross apply (
        select 'Practice' [Page] union all
        select 'Practice ROI' [Page]
    ) p
© www.soinside.com 2019 - 2024. All rights reserved.