Oracle SQL 查询帮助

发布于 2024-12-23 10:05:25 字数 179 浏览 1 评论 0原文

给定一个表:

ID NUMBER
OBJECTID NUMBER
CATEGORYID NUMBER
SCORE NUMBER
SCOREDATE DATE

是否可以在一个查询中有效地检索给定对象的每个不同类别中的最后分数(基于SCOREDATE)?

Given a table:

ID NUMBER
OBJECTID NUMBER
CATEGORYID NUMBER
SCORE NUMBER
SCOREDATE DATE

Is it possible to efficiently retrieve the last score (based on SCOREDATE) in each distinct category for a given object in one query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鱼窥荷 2024-12-30 10:05:25

尝试:

select v.* from (
select category_id, 
       score, 
       scoredate, 
       row_number() over (partition by category_id order by scoredate desc) rn
from MyTable) v
where rn=1

Try:

select v.* from (
select category_id, 
       score, 
       scoredate, 
       row_number() over (partition by category_id order by scoredate desc) rn
from MyTable) v
where rn=1
溺深海 2024-12-30 10:05:25

您想要的内容属于 [greatest-n-per-group] 标记。实现结果的一种方法:

SELECT
    t.CategoryId
  , t.Score
FROM
    ( SELECT
          CategoryId
        , MAX(ScoreDate) AS LastScoreDate
      FROM
          TableX
      WHERE
          ObjectId = @ObjectId
      GROUP BY 
          CategoryId
    ) AS grp
  JOIN
      TableX AS t
    ON  grp.Category = t.CategoryId
    AND grp.LastScoreDate = t.ScoreDate
WHERE
    t.ObjectId = @ObjectId

What you want falls into the [greatest-n-per-group] tag. One way to achieve the result:

SELECT
    t.CategoryId
  , t.Score
FROM
    ( SELECT
          CategoryId
        , MAX(ScoreDate) AS LastScoreDate
      FROM
          TableX
      WHERE
          ObjectId = @ObjectId
      GROUP BY 
          CategoryId
    ) AS grp
  JOIN
      TableX AS t
    ON  grp.Category = t.CategoryId
    AND grp.LastScoreDate = t.ScoreDate
WHERE
    t.ObjectId = @ObjectId
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文