我正在使用mysql,我想为我的选择查询添加一些自定义顺序。
例如,我有这个表名A,有列'a'和'b'。我可以保证'b'比'a'更大。
|a|b|
|3|4|
|1|9|
|2|7|
|6|9|
|8|9|
|2|6|
|4|8|
我想选择它们并按值c = 5排序,订单规则是:
如果c小于a和b,则这是权重1.
如果c在a和b之间,那么这就是权重2.
如果c大于a和b,那么这就是权重3.
然后按此重量值排序。
(此处不需要考虑相同重量的顺序。)
所以结果应该是:
|a|b|
|6|9| -> weight 1
|8|9| -> weight 1
|1|9| -> weight 2
|2|6| -> weight 2
|2|7| -> weight 2
|4|8| -> weight 2
|8|9| -> weight 3
那么我该如何编写这个选择查询呢?
PS:它不必在查询中指定权重1,2和3,我自己发明的权重只是为了解决订单规则!
答案 0 :(得分:3)
您可以使用CASE
:
ORDER BY CASE WHEN @c < a AND @c < b THEN 1
WHEN a < @c AND @c < b THEN 2
WHEN @c > a AND @c > b THEN 3
END
答案 1 :(得分:0)
Select a, b from (
Select a, b,
case when a>5 and b>5 then 1 when a<5 and b>5 then 2 when a<5 and b>5 then 3 end as weight
order by weight)w
答案 2 :(得分:0)
DECLARE @c INT = 5
DECLARE @tab TABLE(a INT, b INT)
INSERT INTO @tab
SELECT 3,4 UNION ALL
SELECT 1,9 UNION ALL
SELECT 2,7 UNION ALL
SELECT 6,9 UNION ALL
SELECT 8,9 UNION ALL
SELECT 2,6 UNION ALL
SELECT 4,8
SELECT *,
CASE WHEN @c < a AND @c < b THEN 1
WHEN @c BETWEEN a AND B THEN 2
WHEN @c > a AND @c > b THEN 3
END
FROM @tab
ORDER BY CASE WHEN @c<a AND @c<b THEN 1
WHEN @c BETWEEN a AND B THEN 2
WHEN @c>a AND @c>b THEN 3
END
答案 3 :(得分:0)
SELECT a, b FROM A
ORDER BY
CASE WHEN a>5 AND b>5 THEN 1
WHEN a < 5 AND 5 < b THEN 2
WHEN 5 > a AND 5 > b THEN 3
END;