计算符合条件的列数

时间:2011-11-06 08:58:17

标签: sql

我的表格[Table]有3列[Column1][Column2][Column3]

我的条件是:

WHERE [Column1] LIKE '%q%' OR [Column2] LIKE '%q%' OR [Column3] LIKE '%q%'

它有效,但我想根据匹配数量来订购结果。

例如

C1 - C2 - C3 
q - q - q
q - a - q
q - a - a

3 个答案:

答案 0 :(得分:2)

在查询中尝试此ORDER BY子句:

ORDER BY (CASE WHEN [Column1] LIKE '%q%' THEN 1 ELSE 0 END +
          CASE WHEN [Column2] LIKE '%q%' THEN 1 ELSE 0 END +
          CASE WHEN [Column3] LIKE '%q%' THEN 1 ELSE 0 END) DESC

答案 1 :(得分:1)

SELECT [Column1], [Column2], [Column3] FROM [Table]
WHERE [Column1] LIKE '%q%' OR [Column2] LIKE '%q%' OR [Column3] LIKE '%q%'
ORDER BY 
    (CASE WHEN [Column1] LIKE '%q%' THEN 1 ELSE 0 END) +
    (CASE WHEN [Column2] LIKE '%q%' THEN 1 ELSE 0 END) +
    (CASE WHEN [Column3] LIKE '%q%' THEN 1 ELSE 0 END)
    DESC

答案 2 :(得分:0)

您应该添加第四列,类似于:

SELECT [Col1],[Col2],[Col3], 
   CAST([Col1] LIKE '%q%' AS SMALLINT) + CAST([Col2] LIKE '%q%' AS SMALLINT) +
   CAST([Col3] LIKE '%q%' AS SMALLINT) AS Strength
....
ORDER BY Strength

由于我不知道您正在使用哪个数据库,因此您可能需要查阅文档以了解如何从布尔值转换为整数。

伊泰