Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

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
like image 765
Jobin Joseph Avatar asked Jun 22 '16 08:06

Jobin Joseph


1 Answers

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
like image 189
Giorgos Betsos Avatar answered Oct 04 '22 11:10

Giorgos Betsos