sql - 每天选择第一个条目
问题描述
我的桌子的结构是这样的
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
要尝试每天仅使用一个条目将表连接到自身,然后从中进行选择,但这不起作用。我对这个很困惑。有任何想法吗?
解决方案
这看起来很复杂。这将返回您想要的结果集:
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)
推荐阅读
- javascript - 如何使组件通用并使其变量可以从外部访问?
- python - Python - 设计一个滑块来控制函数的输入
- javascript - 使用 `keyup` 从我的 `.json' 文件中过滤/搜索已经显示在我的 html 上
- android - 如何在 termux 中更新 Node.js
- algorithm - 如何删除大小为 K 的子数组以最小化数组中的反转次数
- android - java.lang.NullPointerException android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures 在本机反应
- php - SSO 注销和登录问题
- google-cloud-iam - 使用 REST API 生成谷歌云访问令牌不起作用
- javascript - 类型“BaseModel”.ts 上不存在属性“emailAddress”
- python - Pytest Logging 消息出现两次