2017-09-14 17 views
0

このデータはMySQLテーブルにあります。 effective_toNULLある場合、私はMySQL - 条件付き2列で注文

name   effective_from  effective_to 
person 01  1999-04-01   1999-05-31 
person 02  1999-04-01   2000-07-06 
person 03  1999-04-01   2000-09-25 
person 04  1999-04-01   2000-09-25 
person 07  1999-04-01   2000-09-25 
person 05  2013-04-29   NULL 
person 08  2010-06-17   2012-09-27 
person 09  2010-12-02   2012-09-27 
person 10  2017-02-10   NULL 
person 11  2017-02-10   NULL 
person 12  1999-04-01   2000-07-06 
person 13  2011-04-28   2015-10-06 
person 05  2013-04-29   2017-02-15 
person 06  2015-09-22   2017-02-15 
person 06  2015-09-22   2017-02-10 

私のデータ

order by effective_to DESCeffective_toNOT NULLである場合には、第1とorder by effective_from DESC

  • を示しに、

    • :私は、条件によって順序結果を必要としますこの結果が必要な注文

      name    effective_from effective_to             
      person 11  2017-02-10   NULL 
      person 10  2017-02-10   NULL 
      person 05  2013-04-29   NULL 
      person 06  2015-09-22   2017-02-15 
      person 05  2013-04-29   2017-02-15 
      person 06  2015-09-22   2017-02-10 
      person 13  2011-04-28   2015-10-06 
      person 09  2010-12-02   2012-09-27 
      person 08  2010-06-17   2012-09-27 
      person 07  1999-04-01   2000-09-25 
      person 03  1999-04-01   2000-09-25 
      person 04  1999-04-01   2000-09-25 
      person 12  1999-04-01   2000-07-06 
      person 02  1999-04-01   2000-07-06 
      person 01  1999-04-01   1999-05-31 
      

      どうすればよいですか?

  • +0

    異なる 'effective_to'を選択する2つのクエリの' UNION'を使用し、それぞれが希望 'ORDER BY'を使用しています。 – Barmar

    +2

    SOは無料のコーディングサービスではありません。自分で問題を解決しようとする試みが必要です。あなたがそれを働かせることができない場合は、あなたが試したものを投稿してください。 – Barmar

    答えて

    1

    (OPに代わって投稿)行う必要があります。

    私はこのように私の問題を解決:

    ORDER BY `effective_to` IS NOT NULL ASC, `effective_to` DESC, 
        `effective_to` IS NULL, `effective_from` DESC; 
    
    1

    これは

    ... 
    ORDER BY 
    ISNULL(effective_from) DESC, 
    IF(ISNULL(effective_to) = 1, effective_from , effective_to) DESC