Pregunta

I have the following table in Oracle SQL dialect (being called with some java code)

Part # | Locker # | Serial # | Description
  1         1          1       Alpha
  1         1          1       Beta
  1         1          1       Gamma
  2         1          15      Alpha
  2         7          17      Gamma
  2         7          21      Beta

I am looking for a way to do the following sort:

Group part, locker, serial # together and sort the descriptions in ascending or descending order within each group WHILE also making sure the first record for each group is also correctly sorted in ascending or descending order (conflicts should sort in the desired order on part, locker, serial). so for example:

Sorting DESC would yield:

Part # | Locker # | Serial # | Description
  2         7          17      Gamma

  1         1          1       Gamma
  1         1          1       Beta
  1         1          1       Alpha

  2         7          21      Beta

  2         1          15      Alpha

How can I achieve this complex type of sorting? Is it even possible just with a query?

¿Fue útil?

Solución

Interesting challenge, needing to group by 3 fields and select the highest Description for the group, keeping that in the query for sorting.... nice!

I've had a go, in MS-SQL 2008 which can be seen at http://sqlfiddle.com/#!3/422d2/10 There may be an easier way with MS T-SQL Ranking Functions, but this Derived Table of Groups should be fairly easily implemented in other SQLs.

This appears to give the sort order you require :

SELECT
  p1.*, Groups.GMaxDescr
FROM Parts p1 INNER JOIN 
  (SELECT
     p2.Part AS GPart,
     p2.Locker AS GLocker,
     p2.Serial AS GSerial,
     Max(p2.Descr) as GMaxDescr
   FROM Parts p2
   GROUP BY Part, Locker, Serial
  ) AS Groups  -- derived table of Groups with First (Max() for DESC) Name 
      -- join original rows with the Groups data for sorting
       ON p1.Part = Groups.GPart
      AND p1.Locker=Groups.GLocker
      AND p1.Serial=Groups.GSerial
ORDER BY Groups.GMaxDescr DESC,
         Part DESC,
         Locker DESC,
         Serial DESC
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top