如何从SQL中的不同列中查找第一,第二和第三大值

时间:2016-06-22 08:58:44

标签: sql sql-server

嗨我有一个包含J1,J2,J3,J4,J5,J6,J7列的表格。我想从这些列中找到最大的3个值,分别为L1,L2,L3。

我尝试了以下查询来查找第一个

SELECT (
    SELECT Max(v) FROM (
        VALUES 
          ([J1]), ([J2]), 
          ([J3]), ([J4]),
          ([J5]), ([J6]),
          ([J7])
    ) AS value(v)
) as [L1]FROM dbo.JTable

1 个答案:

答案 0 :(得分:6)

如果您的表格中有PK,请说id,那么您可以使用员工UNPIVOT的查询:

SELECT *
FROM (
  SELECT *, 
         ROW_NUMBER() OVER (PARTITION BY id ORDER BY Val) AS rn
  FROM JTable
  UNPIVOT (
     Val FOR Col IN (J1, J2, J3, J4, J5, J6, J7)) AS unpvt) AS t
WHERE t.rn <= 3

如果您想要每id行一行,则可以使用PIVOT撤消UNPIVOT操作:

SELECT id, [1], [2], [3]
FROM (
  SELECT id, Val, rn
  FROM (
    SELECT id, Val, Col,
           ROW_NUMBER() OVER (PARTITION BY id ORDER BY Val) AS rn
    FROM JTable
    UNPIVOT (
       Val FOR Col IN (J1, J2, J3, J4, J5, J6, J7)) AS unpvt) AS t
  WHERE t.rn <= 3) AS src
PIVOT (
   MAX(Val) FOR rn IN ([1], [2], [3])) AS pvt