T-SQL Pivot table 不使用 IN 和基于 MIN() & MAX 的数据透视表中另一列的值

T-SQL Pivot table not using IN and values from another column in the pivot data based on MIN() & MAX

我有一个支点 table 问题,希望得到帮助....

我正在学习的教程没有帮助,因为它们在已知值列表上使用 IN 语句来创建列。

这是我的 IN 语句,我可能会卡住...我正在尝试子查询,但它没有帮助。

SELECT 
    JobDesc, YearExp
FROM
    (SELECT JobDesc, YearExp, Worker 
     FROM Q2) AS SourceTable
PIVOT 
    (MIN(YearExp)
        FOR YearExp IN (SELECT YearExp FROM Q2)
    ) AS PivotTable

数据:

Worker Job Description Years of Experience
1001 Lawyer 6
2002 Lawyer 12
3003 Lawyer 17
4004 Doctor 21
5005 Doctor 9
6006 Doctor 8
7007 Scientist 13
8008 Scientist 2
9009 Scientist 7

我要实现的输出:

Job Description Most Experienced Least Experienced
Lawyer 3003 1001
Doctor 4004 6006
Scientist 7007 8008

window 函数 row_number() over() 与条件聚合相结合应该可以解决问题

Select [Job Description]
      ,[Most]  = max( case when RN1 = 1 then worker end)
      ,[Least] = max( case when RN2 = 1 then worker end)
 From (
        Select * 
              ,RN1 = row_number() over (partition by [Job Description] order by [Years of Experience] desc)
              ,RN2 = row_number() over (partition by [Job Description] order by [Years of Experience] asc)
         from YourTable
      ) A
 Group By [Job Description]

结果

Job Description  Most   Least
Doctor           4004   6006
Lawyer           3003   1001
Scientist        7007   8008

PIVOT 运算符相当不灵活,需要一个固定的列列表来进行透视。

很好,但缺点是需要额外排序,因为行号相反。

这是一个只需要一种排序的解决方案

Select [Job Description]
      ,[Most]  = max( case when NextValue IS NULL then worker end)
      ,[Least] = max( case when RN = 1 then worker end)
 From (
        Select * 
              ,RN = row_number() over (partition by [Job Description] order by [Years of Experience] asc)
              ,NextVal = LEAD([Years of Experience]) over (partition by [Job Description] order by [Years of Experience] asc)
         from YourTable
      ) A
 Group By [Job Description]

LEAD 中的值必须是不可为 null 的值。