PostgreSQL
 sql >> Baza danych >  >> RDS >> PostgreSQL

SQL ORDER BY z CASE z UNION ALL

Umieść wszystko w innym 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

lub lepiej użyj aliasu w ORDER BY, ponieważ jest on przekazywany na końcu 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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Zapytanie read_sql zwraca pustą ramkę danych po przekazaniu parametrów jako dykta w pandach python

  2. Procent sumy w PostgreSQL bez podzapytania

  3. postgres:pobierz wykonywalne zapytanie z zapytania z parametrami

  4. Funkcja śledzenia zależności

  5. Czy WIDOKI PostgreSQL są tworzone od nowa za każdym razem, gdy są odpytywane?