Reputation: 33
I run the following T-SQL query
SELECT [Path],[Access Scope],[Basic Permissions], STRING_AGG([Display Name], ', ') WITHIN GROUP (ORDER BY [Display Name] ASC) AS Accessors
FROM [dbo].[File_Share_Permissions_Report]
GROUP BY [Path],[Access Scope],[Basic Permissions]
ORDER BY [Path]
Which results in a table that looks like this:
Path Access Scope Basic Permissions Accessors
\\network\department\path This folder and subfolders List folder contents Dan, Elroy, Kermit
\\network\department\path This folder, subfolders, and files Full control Jimbob, Tails, Mario
\\network\department\path This folder, subfolders, and files Modify Elly, Waldo, John
And I'm trying to modify the query so that the results look like this:
Path List folder contents -This folder and subfolders Full control - This folder, subfolders, and files Modify - This folder, subfolders, and files
\\network\department\path Dan, Elroy, Kermit Jimbob, Tails, Mario Elly, Waldo, John
I've been struggling on how to do this - any ideas?
Upvotes: 1
Views: 23
Reputation: 7344
Just take the current query as the input table to a pivot query, joining the two cols ([Basic Permissions] and [Access Scope]) into one as the pivot col:
select *
from
(
SELECT [Path],[Access Scope] + ' - ' + [Basic Permissions] PivotOn, STRING_AGG([Display Name], ', ') WITHIN GROUP (ORDER BY [Display Name] ASC) AS Accessors
FROM [dbo].[File_Share_Permissions_Report]
GROUP BY [Path],[Access Scope],[Basic Permissions]
) pvt
pivot (avg(pvt.Accessors) for pvt.PivotOn in
([This folder and subfolders - List folder contents],
[This folder, subfolders, and files - Full control],
[This folder, subfolders, and files - Modify])
) pvted
order by pvted.Path
Upvotes: 1
Reputation: 1269973
Use conditional aggregation -- a CASE
expression:
SELECT [Path], [Access Scope], [Basic Permissions],
STRING_AGG(CASE WHEN [Basic Permissions] = 'List folder contents' THEN [Display Name] END, ', ') WITHIN GROUP (ORDER BY [Display Name] ASC) AS list_Accessors
STRING_AGG(CASE WHEN [Basic Permissions] = 'Full control ' THEN [Display Name] END, ', ') WITHIN GROUP (ORDER BY [Display Name] ASC) AS full_Accessors
STRING_AGG(CASE WHEN [Basic Permissions] = 'Modify' THEN [Display Name] END, ', ') WITHIN GROUP (ORDER BY [Display Name] ASC) AS modify_Accessors
FROM [dbo].[File_Share_Permissions_Report]
GROUP BY [Path],[Access Scope]
ORDER BY [Path]
Upvotes: 1