简体   繁体   English

对SQL Server查询结果进行排名

[英]Ranking SQL Server Query results

Is there a way in SQL Server to rank rows based on the values in the WHERE clause? SQL Server中是否可以根据WHERE子句中的值对行进行排名?

For instance: 例如:

SELECT *
FROM Foo
WHERE 
  Bar1 = true AND
  Bar2 = true OR
  Bar3 = false

The best result in this case would be a row where Bar1 = true, Bar2 = true and Bar3 = false. 在这种情况下,最好的结果是一行,其中Bar1 = true,Bar2 = true,Bar3 = false。 A row where Bar1 = true, Bar2 = true and Bar3 = true would score lower because Bar3 is different. Bar1 = true,Bar2 = true和Bar3 = true的行得分较低,因为Bar3不同。

To make it even more complicated. 使它更加复杂。 The WHERE clause is dynamic, I don't know exactly which columns will appear in the query. WHERE子句是动态的,我不确切知道哪些列将出现在查询中。 So the next query could be: 因此,下一个查询可能是:

SELECT *
FROM Foo
WHERE 
  Bar1 = false OR
  Bar3 = true OR
  Bar4 = True

How can I apply ranking to those queries? 如何将排名应用于这些查询?

Can this be done within the query or is it better to do this in C#? 可以在查询中完成此操作还是在C#中执行此操作更好?

You can order the results by the number of where clauses that match: 您可以按匹配的where子句数对结果进行排序:

order by ((case when Bar1 = true AND Bar2 = true then 1 else end) +
          (case when Bar3 = false then 1 else 0 end)
         ) desc

You could also add this to a field in the select . 您也可以将其添加到select的字段中。 If you are dynamically creating the where , you would have to do the same thing for the order by (or select variable). 如果要动态创建where ,则必须对order by (或select变量)执行相同的操作。

I would advise you to do this in the database, because replicating the logic between SQL and C# seems like a maintenance nightmare. 我建议您在数据库中执行此操作,因为在SQL和C#之间复制逻辑似乎是维护的噩梦。

WITH CTE 
     AS (SELECT T.*, 
                RN = ROW_NUMBER() 
                       OVER ( 
                         ORDER BY BAR1 ASC, BAR2 ASC, BAR3 DESC) 
         FROM   DBO.TABLENAME T) 
SELECT * 
FROM   CTE 
ORDER  BY RN 

You could give each clause a score of 1 if it is satisfied and 0 if it is not satisfied. 您可以给每个子句打分,如果满足,则为1;如果不满足,则为0。 And then you can order by the sum of scores. 然后您可以按分数总和排序。

Something like: 就像是:

SELECT *
FROM Foo
ORDER BY cast((Bar1 = true) as int)
       + cast((Bar2 = true OR Bar3 = false) as int)
DESC

Don't know what do you mean by true in SQL Server. 不知道是什么做你的意思true在SQL Server中。 If you Bars are bit columns, you can rank like this: 如果条形图是位列,则可以这样排列:

select *
from Foo
order by
    case
       when Bar1 = 1 and Bar2 = 1 and Bar3 = 0 then 0
       else 1
    end asc

if it's strings: 如果是字符串:

select *
from Foo
order by
    case
       when Bar1 = 'true' and Bar2 = 'true' and Bar3 = 'false' then 0
       else 1
    end asc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM