[英]How Can I Write a SQL Query That Will Sort the Results Based on a Condition?
SELECT t1.LogEntryID, t1.Value, t1.ThresholdID,
case when t1.Value < t2.threshold then 1 else 0 end as Rank
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.ThresholdID = t2.ThresholdID
ORDER By Rank
如果您想要相反的順序,可以在ORDER By Rank
之后添加DESC
。
與OrbMan給出的答案類似,但我更喜歡CASE在ORDER BY中顯式,因此您不必按列顯示您的訂單。
SELECT
t1.LogEntryID
,t1.Value
,t1.ThresholdID
FROM
Table1 t1
JOIN Table2 t2 ON t2.ThresholdID = t1.ThresholdID
ORDER BY
CASE WHEN t1.Value < t2.threshold
THEN 1
ELSE 0
END ASC
只是一個想法,但你不能使用'閾值 - 值'作為你的返回列之一?
如果您這樣做(並且列是數字的),您還可以看到該值與閾值的接近程度(或遠)。
任何積極的或0都將低於門檻,任何負面的東西都不會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.