我目前正在嘗試撰寫一個 SQL 查詢,該查詢是前 100 行,其中兩個值的百分比增幅最大。我目前的解決方案是這樣寫我的查詢:
//NULL is also not accepted in where clause, shortened version
SELECT TOP 100 id, name, currentValue, pastDayValue FROM comparables
WHERE NOT pastDayValue = currentValue AND NOT pastDayValue = 0 AND NOT currentValue = 0
ORDER BY (currentValue - pastDayValue) / (currentValue / 100) desc;
唯一的問題是:可能會出現值為零或相同的情況,盡管我確實想過濾掉這些值(請參閱 where 子句),但我仍然收到 System.Data.SqlException 'Divide by zero'來自 order by 子句。
我已經做了一些研究,據我所知, where 子句應該在 order by 之前執行,因此過濾掉任何零值(表也可以有 NULL 值,我也在 where 子句中進行了轉義,只是沒有將它包含在上面的查詢中以使其更短)。我看到的唯一防止這種情況的方法是 NULLIF 或 CASE 子句,但我不確定如何將它們處理到我的 order by 陳述句中。
我很感激有關如何解決此問題的任何想法!(注意:我正在研究 SQL-Server 2019)
uj5u.com熱心網友回復:
這可能是由整數值 (currentValue) 除以整數值引起的。如果整數被除數除以整數除數,小數將被截斷。
請參閱:https : //docs.microsoft.com/en-us/sql/t-sql/language-elements/divide-transact-sql?view=sql-server-ver15
一個可能的解決方案是將整數 100 更改為十進制數,如下所示:
ORDER BY (currentValue - pastDayValue) / (currentValue / 100.0) desc;
uj5u.com熱心網友回復:
ORDER BY (currentValue - pastDayValue) / (currentValue / 100.0) desc;
情商
ORDER BY (currentValue - pastDayValue) / (currentValue) desc;
情商
ORDER BY (currentValue) / (currentValue) - (pastDayValue) / (currentValue) desc;
情商
ORDER BY 1 - pastDayValue / currentValue desc;
情商
ORDER BY pastDayValue / currentValue asc;
uj5u.com熱心網友回復:
你的錯誤是:
“ where 子句應該在 order by 之前執行,因此過濾掉任何零值”
這絕對不是真的。它指的是 的邏輯執行WHERE,但編譯器經常會重新排列查詢以利用索引等。它沒有考慮的一件事是可能的例外,這意味著ORDER BY運算式的計算可能發生在WHERE和之前例外。因此,您必須使用NULLIF或消除零CASE
SELECT TOP (100)
id,
name,
currentValue,
pastDayValue
FROM comparables
WHERE pastDayValue <> currentValue
AND pastDayValue <> 0
AND currentValue <> 0
ORDER BY (currentValue - pastDayValue) / NULLIF(currentValue, 0) DESC;
--alternatively
ORDER BY pastDayValue / NULLIF(currentValue, 0) ASC;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397718.html
標籤:C# sql sql-server
下一篇:如何合并兩個表以顯示條目歷史更改
