【问题标题】:T-SQL Pivot table not using IN and values from another column in the pivot data based on MIN() & MAXT-SQL 数据透视表不使用 IN 和基于 MIN() 和 MAX 的数据透视数据中另一列的值
【发布时间】:2022-01-11 05:17:13
【问题描述】:

我有一个数据透视表问题,希望得到帮助....

我所关注的教程没有帮助,因为它们在已知值列表上使用 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

【问题讨论】:

  • 您不能使用子查询或任何其他类型的表达式,它必须是文字

标签: sql sql-server tsql pivot-table


【解决方案1】:

窗口函数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

【讨论】:

  • @markSS 总是乐于提供帮助。顺便说一句,窗口函数是无价的。值得您花时间尝试它们
【解决方案2】:

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

answer given by @JohnCappelletti 很好,但它的缺点是需要额外的排序,因为行号相反。

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

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 中的值必须是不可为空的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 2018-02-23
    相关资源
    最近更新 更多