首页 > 解决方案 > 每天选择第一个条目

问题描述

我的桌子的结构是这样的

temp
ID | Date
---|-----------
1  | 2018-01-01
2  | 2018-01-01
3  | 2018-01-01
4  | 2018-01-02
5  | 2018-01-02
6  | 2018-01-03

我将从用户那里获得开始和结束日期的输入:

@StartDate DATE = '2018-01-01'
@EndDate DATE = '2018-01-03'

我希望我的回报结构如下:

ID | Date
---|-----------
1  | 2018-01-01
4  | 2018-01-02
6  | 2018-01-03

我试过这样做:

select distinct temp.ID, joinTable.Date
from temp
inner join (
            select min(innerTemp.Date), innerTemp.ID
            from temp innerTemp
            where innerTemp.Date >= @StartDate
            and innerTemp.Date < @EndDate
            group by innerTemp.ID, innerTemp.Date
           ) as joinTable on joinTable.ID = temp.ID and joinTable.Date = temp.Date
where temp.Date >= @StartDate
and temp.Date < @EndDate
order by temp.Date desc

要尝试每天仅使用一个条目将表连接到自身,然后从中进行选择,但这不起作用。我对这个很困惑。有任何想法吗?

标签: sqlsql-server

解决方案


这看起来很复杂。这将返回您想要的结果集:

select min(id), date
from temp
where date >= @StartDate and date < @EndDate
group by date;

如果您有其他要保留的列(所以group by不合适),一个性能良好的简单方法是:

select t.*
from temp t
where t.id = (select min(t2.id) from temp t2 where t2.date = t.date and t2.date >= @StartDate and t2.date < @EndDate);

当然,你也可以使用,但是在androw_number()上有一个索引,上面应该很快。temp(date, id)temp(id)


推荐阅读