sql >> データベース >  >> RDS >> PostgreSQL

UNIONALLを使用したCASEを使用したSQLORDERBY

    すべてを別の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
    

    または、UNIONの最後に渡されるため、ORDER BYでエイリアスを使用することをお勧めします:

      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 JDBCドライバー接続文字列とは何ですか?

    2. PHPへのMySQLpassword()関数

    3. SQLの2つの文字列を比較します[最初の文字列には2番目の文字列のサブ文字列が含まれます]

    4. 毎日のアクセスを制限する