在ORDER BY语句中计算CASE

时间:2013-06-28 06:38:34

标签: sql

不幸的是,我的SQL非常生疏。我目前有这样的声明:

SELECT field1, field2, field3 FROM table_name WHERE
    field1 = 'A' OR field2 = 'B' OR field3 = 'C' ORDER BY
        CASE WHEN field1 = 'A' THEN 1 ELSE 0 END +
        CASE WHEN field2 = 'B' THEN 1 ELSE 0 END +
        CASE WHEN field3 = 'C' THEN 1 ELSE 0 END
    DESC LIMIT 1;

此查询正确地找到与field1field2field3AB的“理想”最相似的项目,以及分别为C。但是,我也希望能够找到“匹配”字段数量的计数。看起来我应该能够轻松搞定,因为我已经执行了这个计算但是我不确定如果没有其他子查询。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

<强>已更新

SELECT field1, field2, field3,
       CASE WHEN field1 = 'A' THEN 1 ELSE 0 END +
       CASE WHEN field2 = 'B' THEN 1 ELSE 0 END +
       CASE WHEN field3 = 'C' THEN 1 ELSE 0 END match_count
  FROM table_name 
 WHERE field1 = 'A' OR field2 = 'B' OR field3 = 'C' 
 ORDER BY match_count DESC

在这种特殊情况下(对于 MySql ),您可以将CASE替换为(fieldX = 'N')

SELECT field1, field2, field3,
       (field1 = 'A') + (field2 = 'B') + (field3 = 'C') match_count
  FROM table_name 
 WHERE field1 = 'A' OR field2 = 'B' OR field3 = 'C' 
 ORDER BY match_count DESC

现在基于match_count限制结果集使用HAVING子句

SELECT field1, field2, field3,
       (field1 = 'A') + (field2 = 'B') + (field3 = 'C') match_count
  FROM table_name 
 WHERE field1 = 'A' OR field2 = 'B' OR field3 = 'C' 
HAVING match_count > 1
 ORDER BY match_count DESC

以上是所有上述查询的 SQLFiddle 演示