在单个请求中从多个列中获取唯一值

Get unique values from multiple columns in single request

我有一个包含多个列的员工数据。我有一个 WebAPI,它正在从这个数据库中读取一个显示用户的搜索应用程序。我需要获取其中 4 个字段的唯一值列表。如果可能,我希望在单个查询中执行此操作。

我有超过 25 个列,但我需要 4 个列(JobTitle、Department、Position、Group)的唯一值。我只需要它们 return 作为逗号分隔的列表。

示例 SQL 服务器 2016 Table:

  Name | JobTitle |  Department  |  Position  |  Group  
 ------|----------|--------------|------------|--------- 
  John |  Partner |  Department1 |  Position1 |  Group1 
  Jane |  Manager |  Department2 |  Position2 |  Group2 
  Joe  |  Analyst |  Department2 |  Position2 |  Group2 

我希望我的结果是单行,其中包含以逗号分隔的唯一值列表:

单行returned

Departments: Department1,Department2
JobTitles: Partner,Manager,Analyst
Positions: Position1,Position2
Groups: Group1, Group2

直到 SQL Server 2016,您可以使用 STUFF 将来自不同行的字符串连接成一个 Row/Column,并使用逗号分隔符。以下脚本将根据您的要求 return DISTINCT 值列表-

SELECT DISTINCT
STUFF((SELECT DISTINCT  ',' + A.JobTitle FROM Employee A FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') JobTitle, 
STUFF((SELECT DISTINCT  ',' + A.Department FROM Employee A FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') Department,
STUFF((SELECT DISTINCT  ',' + A.Position FROM Employee A FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') Position,
STUFF((SELECT DISTINCT  ',' + A.[Group] FROM Employee A FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') [Group]
FROM Employee A

如果要在不同值列表之前添加标签,请使用以下脚本-

SELECT 
'JobTitles: ' + B.JobTitle AS  JobTitle,
'Departments: ' + B.Department AS  Department,
'Positions: ' + B.Position AS  Position,
'Groups: ' + B.[Group] AS  [Group]
FROM
(
    SELECT DISTINCT
    STUFF((SELECT DISTINCT  ',' + A.JobTitle FROM Employee A FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') JobTitle, 
    STUFF((SELECT DISTINCT  ',' + A.Department FROM Employee A FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') Department,
    STUFF((SELECT DISTINCT  ',' + A.Position FROM Employee A FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') Position,
    STUFF((SELECT DISTINCT  ',' + A.[Group] FROM Employee A FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') [Group]
    FROM Employee A
)B