我已經為一個問題苦苦掙扎了好幾個小時。我發現自己陷入了多個兔子洞并進入了 DeCorrelated SubQueries 的領域,坦率地說,這超出了我的范圍......
我有兩個表,我試圖從兩個表中提取而沒有一個共同的列來加入。我需要從表 1 中取一個值,在表 2 中找到最接近的值(即較低),然后從表 2 中提取相關資料。
表格1
| ID | 分數 |
|---|---|
| 1 | 99.983545 |
| 2 | 98.674359 |
| 3 | 97.832475 |
| 4 | 96.184545 |
| 5 | 93.658572 |
| 6 | 89.963544 |
| 7 | 87.427353 |
| 8 | 82.883345 |
表_2
| 平均水平 | 百分位數 |
|---|---|
| 99.743545 | 99 |
| 97.994359 | 98 |
| 97.212485 | 97 |
| 96.987545 | 96 |
| 95.998573 | 95 |
| 88.213584 | 94 |
| 87.837384 | 93 |
| 80.982147 | 92 |
從上面的兩個表中,我需要:
- 取id和score
- 確定最接近分數的average_level
- 包括相關的 average_level 和 percentile
希望的輸出看起來像這樣......
| ID | 分數 | 平均水平 | 百分位數 |
|---|---|---|---|
| 1 | 99.983545 | 99.743545 | 99 |
| 2 | 98.674359 | 97.994359 | 98 |
| 3 | 97.832475 | 97.212485 | 97 |
| 4 | 96.184545 | 95.998573 | 95 |
| 5 | 93.658572 | 88.213584 | 94 |
| 6 | 89.963544 | 88.213584 | 94 |
| 7 | 87.427353 | 80.982147 | 92 |
| 8 | 82.883345 | 80.982147 | 92 |
任何幫助或建議將不勝感激
uj5u.com熱心網友回復:
您可以通過使用 table_1.score >= table_2.average_level 連接兩個表然后獲取 max(average_level) 和 max(average_level) - 這將是來自 table_2 的壁櫥但較低或相等的值 - 并按欄位分組表格1:
SELECT TABLE_1.ID, TABLE_1.SCORE,
MAX(TABLE_2.AVERAGE_LEVEL) AS AVERAGE_LEVEL,
MAX(TABLE_2.PERCENTILE) AS PERCENTILE
FROM TABLE_1 INNER JOIN TABLE_2
ON TABLE_1.SCORE >= TABLE_2.AVERAGE_LEVEL
GROUP BY TABLE_1.ID, TABLE_1.SCORE
ORDER BY TABLE_1.ID
我在這里添加了小提琴示例,它還包括@?mer 的答案
uj5u.com熱心網友回復:
如果我們說第一個表得分 和第二個平均得分, 你可以試試這個。
select *
from Score s
inner join average a on a.Percentile = (select top(1) al.Percentile from average al order by Abs(average_level - s.score))
在此處輸入影像描述
uj5u.com熱心網友回復:
在百分位表上使用lag函式來附加下一個較高行的值,例如:
| l_level | l_percentile | u_level | u_percentile |
|---|---|---|---|
| 99.743545 | 99 | 空值 | 空值 |
| 97.994359 | 98 | 99.743545 | 99 |
| 97.212485 | 97 | 97.994359 | 98 |
| 96.987545 | 96 | 97.212485 | 97 |
現在使用以下條件將其與分數表連接:
on score >= l_level
and (score < u_level or u_level is null)
這會將每個分數與一個范圍相結合。為了找出分數值是更接近下限還是上限,只需使用case:
case when u_level - score < score - l_level then u_level else l_level end,
case when u_level - score < score - l_level then u_percentile else l_percentile end,
理論上,視窗函式應該比自連接提供更好的性能。
使用 SQL Server 的 DBFiddle
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/437065.html
