【问题标题】:How to perform a result limit by using distinct values in a specific column?如何通过在特定列中使用不同的值来执行结果限制?
【发布时间】:2018-11-10 09:22:54
【问题描述】:

鉴于我有这个数据集。

Player         Team         Date_Played
John Smith     New York     2/25/2014
Joe Smith      New York     2/25/2014
Steve Johnson  New York     2/25/2014
Steph Curry    Orlando      2/25/2014
Frank Anthony  Orlando      2/26/2014
Brian Smith    Bulls        2/26/2014
Steve Johnson  Bulls        2/27/2014
Steph Curry    Bulls        2/28/2014
Ben Smith      Bulls        3/28/2014

我想知道如何编写一个返回每支球队一半球员数量的查询。我希望它看起来像这样:

Player         Team         Date_Played
John Smith     New York     2/25/2014
Joe Smith      New York     2/25/2014
Steph Curry    Orlando      2/25/2014
Brian Smith    Bulls        2/26/2014
Steve Johnson  Bulls        2/27/2014

我考虑过尝试使用 LIMIT 或 TOP 命令,但我不知道如何编写查询来根据特定列中的不同值限制结果。 有任何想法吗?这可能吗?

【问题讨论】:

  • 为什么选择 PL/SQL?这可以在一个简单的 SQL 查询中完成。
  • 哪一半?为什么是 John 和 Joe 而不是 Steve?
  • @wolφi 这似乎是一个常见的误解,即 PL/SQL 与“使用 Oracle 数据库的 SQL”相同,而不是“Oracle 关系数据库中 SQL 的过程语言扩展”,所以问题经常得到错误标记 - 只需更正标签/标题即可删除对 PL/SQL 的不当引用。
  • 感谢@MT0 的更正

标签: sql oracle greatest-n-per-group


【解决方案1】:

您可以使用窗口函数。我会使用row_number()count()

select t.*
from (select t.*, count(*) over (partition by team) as cnt,
             row_number() over (partition by team order by team) as seqnum
      from t
     ) t
where seqnum <= 0.5 * cnt;

还有其他方法使用单个函数,例如ntile()

select t.*
from (select t.*, 
             ntile(2) over (partition by team order by team) as tile
      from t
     ) t
where tile = 1;

percentile() 或其他人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2020-02-07
    相关资源
    最近更新 更多