gpt4 book ai didi

mysql - 多列的条件排序依据

转载 作者:行者123 更新时间:2023-11-29 06:04:14 29 4
gpt4 key购买 nike

我有以下查询:

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

最佳答案

试试这个:

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

关于mysql - 多列的条件排序依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42765820/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com