sql >> Database teknologi >  >> RDS >> PostgreSQL

SQL ORDER BY med CASE med UNION ALL

Læg alt i en anden SELECT:

SELECT * FROM (
  SELECT "Field1" AS field_1, "Field2" AS field_2,
  "Field3" AS field_3, "Field4" AS field_4
  FROM "TableName" 
  WHERE condition
  AND other_condition
  UNION ALL
  SELECT "Field1" AS field_1, "Field2" AS field_2,
  "Field3" AS field_3, "Field4" AS field_4
  FROM "TableName" 
  WHERE yet_another_condition
  AND yet_another_other_condition
) As A
ORDER BY CASE field_1
    WHEN 'A' THEN 1
    WHEN 'B' THEN 2
    WHEN 'C' THEN 3
    ELSE 4
END
 

eller bedre, brug aliaset i ORDER BY, som det sendes i slutningen af ​​UNION:

SELECT "Field1" AS field_1, "Field2" AS field_2, "Field3" AS field_3, "Field4" AS field_4 FROM "TableName" WHERE condition AND other_condition UNION ALL SELECT "Field1" AS field_1, "Field2" AS field_2, "Field3" AS field_3, "Field4" AS field_4 FROM "TableName" WHERE yet_another_condition AND yet_another_other_condition ORDER BY CASE field_1 WHEN 'A' THEN 1 WHEN 'B' THEN 2 WHEN 'C' THEN 3 ELSE 4 END

  1. mysql hvis ikke eksisterer

  2. databaseforespørgsel for at finde tog mellem to stationer på en bestemt dato som irctc.co.in

  3. Udødelig Oracle-session venter på SQL*Net-meddelelse fra klienthændelse

  4. Oversigt over datakomprimering i SQL Server