簡體   English   中英

如何編寫將根據條件對結果進行排序的SQL查詢?

[英]How Can I Write a SQL Query That Will Sort the Results Based on a Condition?

of mine, and uses all of the same basic info. 這個問題是基於 我的 ,並使用了所有相同的基本信息。 該鏈接顯示了我的表格布局和簡單連接的基本要點。

, and simply sort them by whether or not Value is less than the linked Threshold. 我想編寫另一個查詢,從選擇每條記錄,然后根據Value是否小於鏈接閾值對它們進行排序。

再一次,我感謝任何願意接受這一點的人。 數據庫從來都不是我的強項。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM