SQL 查询帮助 - 需要一些魔法
我需要一些查询帮助 - 我正在使用 Firebird 2.1。
我有一张表,如下所示:
RowID (primary key) | ActivityID | Duration | BilledAt
1 | 1 | 50 | 06.08.2010, 14:05:00.598
2 | 1 | 70 | 06.08.2010, 14:05:00.608
3 | 2 | 30 | 06.08.2010, 14:05:00.598
4 | 3 | 40 | 06.08.2010, 14:05:00.598
5 | 3 | 50 | 06.08.2010, 14:05:00.608
我想获取每个 ActivityID 的持续时间,但如果有多个条目具有相同的 ActivityID,我需要获取具有最高 BilledAt 值的条目。 (最新条目)
如果我执行:
SELECT ActivityID, Max(BilledAt)
FROM BilledTime
GROUP BY ActivityID;
我将得到我想要的东西,而无需持续时间值。如果我在 GROUP BY 子句中包含 Duration 列,则会选择多个 ActivityID。
有一个优雅的解决方案吗?
谢谢!
I need some help with a query - I'm using Firebird 2.1.
I have a table like:
RowID (primary key) | ActivityID | Duration | BilledAt
1 | 1 | 50 | 06.08.2010, 14:05:00.598
2 | 1 | 70 | 06.08.2010, 14:05:00.608
3 | 2 | 30 | 06.08.2010, 14:05:00.598
4 | 3 | 40 | 06.08.2010, 14:05:00.598
5 | 3 | 50 | 06.08.2010, 14:05:00.608
I'd like to get the Durations for each ActivityID BUT if there are more than one entries available with the same ActivityID, I need the get the one with the highest BilledAt value. (the most recent entry)
If I execute:
SELECT ActivityID, Max(BilledAt)
FROM BilledTime
GROUP BY ActivityID;
I'll get what I want without the Duration values. If I include the Duration column in the GROUP BY clause, then multiple ActivityIDs are selected.
Is there an elegant solution to this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不熟悉 Firebird,因此语法可能是错误的,但这应该可行:
或者您可以使用更直观的 WHERE NOT EXISTS 子查询而不是 LEFT JOIN,但我相信上面的结果会更快。
Not familiar with Firebird so the syntax might be wrong, but this should work:
Alternatively you can use a more intuitive WHERE NOT EXISTS subquery instead of the LEFT JOIN, but I believe the above ends up being faster.
我会这样做
I would do like this