Jobin Joseph Jobin Joseph - 5 months ago 10
SQL Question

how to find first, second and third largest values from different columns in SQL

Hi I have a table with columns J1,J2,J3,J4,J5,J6,J7. I want to find the largest 3 values from these columns as L1,L2,L3.

I tried the below query to find the first largest

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

Answer

If your table has a PK, say id, then you can use a query that employees 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

If you want one row per id, then you can use PIVOT to undo the UNPIVOT operation:

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