嗨我有一个包含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
答案 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