简体   繁体   English

Pivot这个SQL表怎么办?

[英]How to Pivot this SQL Table?

I run the following T-SQL query我运行以下 T-SQL 查询

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?我一直在为如何做到这一点而苦苦挣扎——有什么想法吗?

Use conditional aggregation -- a CASE expression:使用条件聚合——一个CASE表达式:

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]

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:只需将当前查询作为 pivot 查询的输入表,将两个列([基本权限] 和 [访问范围])合并为 pivot 列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM