【问题标题】:SQL query to limit number of rows having distinct valuesSQL查询以限制具有不同值的行数
【发布时间】:2011-06-20 03:58:25
【问题描述】:

SQL 中有没有一种方法可以使用相当于以下内容的查询:

select * from table1, table2 where some_join_condition
and some_other_condition and count(distinct(table1.id)) < some_number;

假设 table1 是一个员工表。然后,连接将导致有关单个员工的数据分布在多行中。我想将返回的不同员工的数量限制为某个数量。在这种情况下,行号或类似条件是不够的。

那么,获得与上述查询预期的相同输出相同效果的最佳方法是什么?

【问题讨论】:

    标签: sql mysql database oracle pagination


    【解决方案1】:
    select *
    from (select * from employee where rownum < some_number and some_id_filter), table2
    where some_join_condition and some_other_condition;
    

    【讨论】:

    • 哦,是的!这很简单。我早该想到的。
    【解决方案2】:

    这几乎适用于所有数据库

    SELECT * 
    FROM table1 t1
    INNER JOIN  table2 t2
    ON some_join_condition
       AND some_other_condition 
    INNER JOIN ( 
        SELECT t1.id
        FROM table1 t1
        HAVING 
            count(t1.ID) > someNumber
        ) on t1.id = t1.id
    

    一些 DB 有特殊的语法,使这更容易一些。

    【讨论】:

      【解决方案3】:

      我可能不完全了解您要完成的工作,但假设您尝试将其减少到每位员工 1 行,但每次加入都会导致每位员工多行并按员工姓名分组并且其他字段仍然不够独特,无法将其归为一行,那么您可以尝试使用排名和分区,然后为每个员工分区选择您喜欢的排名。

      查看示例:http://msdn.microsoft.com/en-us/library/ms176102.aspx

      【讨论】:

        猜你喜欢
        • 2013-02-23
        • 2016-05-21
        • 2018-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        相关资源
        最近更新 更多