排序SQL Server查询结果

时间:2013-09-02 15:38:17

标签: c# sql sql-server

SQL Server中是否有办法根据WHERE子句中的值对行进行排名?

例如:

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

在这种情况下,最好的结果是一行,其中Bar1 = true,Bar2 = true,Bar3 = false。 Bar1 = true,Bar2 = true且Bar3 = true的行将得分较低,因为Bar3不同。

使它变得更加复杂。 WHERE子句是动态的,我不确切知道哪些列将出现在查询中。所以下一个查询可能是:

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

如何对这些查询应用排名?

这可以在查询中完成,还是最好在C#中执行此操作?

4 个答案:

答案 0 :(得分:1)

您可以按照匹配的where子句的数量来排序结果:

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

您也可以将其添加到select中的字段中。如果您要动态创建where,则必须对order by(或select变量)执行相同的操作。

我建议你在数据库中这样做,因为复制SQL和C#之间的逻辑似乎是一个维护噩梦。

答案 1 :(得分:0)

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 

答案 2 :(得分:0)

如果满足,则每个子句的得分为1,如果不满足则为0。然后你可以通过总分来订购。

类似的东西:

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

答案 3 :(得分:0)

不知道SQL Server中true是什么意思。如果Bars是位列,您可以这样排名:

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

如果是字符串:

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