我正在使用的查詢:
select SUM(marks)
from Table1
where name = ?
and Date = (select top 1 Date
from Table1
where name =?
and Date < ?
order by Date desc)
表格1:
| ID | 名稱 | 分數 | 日期 |
|---|---|---|---|
| 1 | 美國廣播公司 | 34 | 01/01/2021 |
| 2 | 美國廣播公司 | 15 | 05/01/2021 |
| 3 | 美國廣播公司 | 20 | 05/01/2021 |
| 4 | 定義 | 34 | 05/01/2021 |
| 5 | 美國廣播公司 | 12 | 10/01/2021 |
select sum(marks)
from Table1
where name ='abc'
and Date = (select top 1 Date
from Table1
where name = 'abc'
and Date < 10/01/2021
order by Date desc)
結果 35
uj5u.com熱心網友回復:
使用RANK()時間相對較短:
select sum(marks)
from
(
select *, rank()OVER(order by date desc) as rnk
from table1
where name ='abc' and Date < '10/01/2021'
) as we
where rnk=1
結果: 35
解釋:
您的查詢在 WHERE 子句中使用子查詢,它將檢查每個條件,并且您過濾名稱abc2 次。或者,我只做一次并在FROM子句中提供子查詢,這大大節省了時間。
看看這里的演示隨著時間的流逝(制作了一些額外的虛擬資料來檢查時間)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/389543.html
標籤:sql sql-server 查询语句
上一篇:如何使用LIMIT獲取行的總和
