![](/img/trans.png)
[英]How to get the previous and next record based on creation date and group by another column in a single query?
[英]single query to get all matches based on a field in a previous result
我有一個包含三個字段的表:名稱(字符串)id(數字)日期(時間)
我需要一個查詢,該查詢將返回日期范圍內的所有匹配項,然后為每個匹配項返回具有相同ID的所有其他匹配項。
即如果:
John 100 1/1/2000
Karen 200 1/1/2000
Tom 300 2/1/2000
Janet 100 3/1/2000
我需要一個查詢,即對於日期范圍,即1-1 / 1/2000,將同時返回John,Karen和Janet-John和Karen在日期范圍內,而Janet因為具有相同的ID(100)之一日期結果中的ID(John)。
對我來說,了解結果的順序也很重要,因為我需要將結果轉換為以下形式的JSON:
[ [ dateMatch1, extraIDmatch1, extraIdmatch2 ], [ dateMatch2] ]
或在這種情況下[[''John','Janet'],['Karen']]
實現此目標的最佳方法是什么?
謝謝!
一種方法是:
select t.*
from t
where t.id in (select t2.id
from t t2
where t2.date between @start and @end
)
order by id, (case when t.date between @start and @end then 1 else 2 end);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.