SQL Server Compare list with a second list in MS Azure sql [closed]

yshpjwxd  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(131)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed 3 days ago.
This post was edited and submitted for review 3 days ago.
Improve this question

This is in Microsoft Azure. I have a list of reports that have specific organizations associated with it. For example

  1. CREATE TABLE Reports (
  2. reportId INT,
  3. OrganizationID INT
  4. );
  5. INSERT INTO Reports (reportId, OrganizationID) VALUES
  6. (1, 1),
  7. (1, 2),
  8. (2, 1),
  9. (3, 1),
  10. (3, 2),
  11. (3, 3);

I also have a user table that's associated to organizations. For example:

  1. CREATE TABLE Users (
  2. User CHAR(1),
  3. OrganizationId INT
  4. );
  5. INSERT INTO Users (User, OrganizationId) VALUES
  6. ('a', 1),
  7. ('a', 2),
  8. ('b', 2),
  9. ('c', 1),
  10. ('c', 2),
  11. ('c', 4);

What I need to do is figure out who has access to which report based on their organizations - the user has to have all the organizations that are listed in the report in order to have access to that report. So with the above data I would expect to see user a has access to both report 1 and report 2, user b doesn't get access to any reports and user c gets access to report 1 and report 2.

Output example:
| User | ReportId |
| ------------ | ------------ |
| a | 1 |
| a | 2 |
| c | 1 |
| c | 2 |

I know I can use a SQL to loop through the reports one by one to figure out who has access to which report, is there a way to do that without looping through the reports and just in straight SQL? Would appreciate any help! Thanks in advance.

z6psavjg

z6psavjg1#

To identfy if a user has permissions to all the organisations that a report covers, use a combination of group by and having clauses. Here it compares the number of organizations the user has to the number of organizations the report covers (note the join conditions requires the organizations to match per row).

  1. SELECT
  2. r.reportId
  3. , u.User_
  4. FROM Reports r
  5. INNER JOIN Users u ON r.OrganizationID = u.OrganizationId
  6. GROUP BY
  7. r.reportId
  8. , u.User_
  9. HAVING COUNT(DISTINCT r.OrganizationID) = (
  10. SELECT COUNT(DISTINCT OrganizationID)
  11. FROM Reports r2
  12. WHERE r2.reportId = r.reportId
  13. )
reportIdUser_
1a
1c
2a
2c

see this SQL Server fiddle

Please note that the having clause is designed to allow for filtering via aggregated values. As such it sites after the group by clause and it is absolutely NOT a substitute for a where clause. You can use both in the same query.

展开查看全部

相关问题