多列上的条件顺序

时间:2017-03-13 14:16:01

标签: mysql

我有以下查询:

SELECT year, month, btype, bnumber 
FROM some_table 
ORDER BY year ASC, month ASC, bnumber ASC, btype ASC 

btype具有以下值

block
week
month

btype = blockbnumber = 1我希望它成为表格中的第一个值时。但是,当btype = blockbnumber = 2我希望它在所有其他bnumber = 2值之后。

以下是查询当前返回值的方式:

year    month   btype   bnumber
======  ======  ======  ======
2017    3       block   1
2017    3       month   1
2017    3       week    1
2017    3       block   2
2017    3       week    2
2017    3       week    3
2017    3       week    4

我希望结果如下:

year    month   btype   bnumber
======  ======  ======  ======
2017    3       block   1
2017    3       month   1
2017    3       week    1
2017    3       week    2
2017    3       block   2
2017    3       week    3
2017    3       week    4

使用CASE是否可以这样?我尝试了几种不同的变化,但似乎无法让它发挥作用。这是我尝试将btype = blockbnumber = 2视为bnumber = 3的最后一句话,但它不起作用:

ORDER BY year ASC, month ASC, 
         CASE btype 
            WHEN 'block' and bnumber = '2' THEN bnumber = '3' 
            ELSE 1 
         END ASC, 
         bnumber ASC, 
         btype ASC

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT year, month, btype, bnumber
FROM some_table
ORDER BY year ASC, month ASC, 
         CASE 
            -- Place btype ='block' / bnumber = '1' at the first place
            WHEN btype ='block' and bnumber = '1' THEN 1
            -- Prioritize bnumber = '2' / btype <> 'block' over 
            -- bnumber = '2' / btype = 'block'
            WHEN bnumber = '2' THEN CASE 
                                      WHEN btype <> 'block' THEN 1.1
                                      ELSE 1.2
                                    END            
            ELSE bnumber  
         END ASC, 
         bnumber ASC, 
         btype ASC

Demo here

答案 1 :(得分:1)

这样的东西会满足规范:

ORDER
   BY year
    , month
    , bnumber
    , CASE
        WHEN btype = 'block' AND bnumber > 1 
        THEN 'zzz'
        ELSE btype
      END

CASE表达式通常会返回btype的值,这是我们在bnumber上订购后通常想要按字母顺序排序的。

我们处理&#34;特殊&#34; btype='block' and bnumber>1的情况...我们不会返回btype,而是返回特殊的高价值&#39; zzz&#39;这比btype的所有其他值都要高。

更强大的解决方案将在btype列之前的ORDR BY中使用单独的表达式:

ORDER 
   BY year
    , month
    , bnumber
    , CASE
        WHEN btype = 'block' AND bnumber > 1 
        THEN 1
        ELSE 0
      END
    , btype