[英]Ranking SQL Server Query results
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#中執行此操作更好?
您可以按匹配的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#之間復制邏輯似乎是維護的噩夢。
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
您可以給每個子句打分,如果滿足,則為1;如果不滿足,則為0。 然后您可以按分數總和排序。
就像是:
SELECT *
FROM Foo
ORDER BY cast((Bar1 = true) as int)
+ cast((Bar2 = true OR Bar3 = false) as int)
DESC
不知道是什么做你的意思true
在SQL Server中。 如果條形圖是位列,則可以這樣排列:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.