SQL 查询限制具有不同值的行数

发布于 2024-10-15 12:34:38 字数 320 浏览 4 评论 0原文

SQL 中有没有一种方法可以使用与以下内容等效的查询:

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

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

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

Is there a way in SQL to use a query that is equivalent to the following:

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

Let us say table1 is an employee table. Then a join will cause data about a single employee to be spread across multiple rows. I want to limit the number of distinct employees returned to some number. A condition on row number or something similar will not be sufficient in this case.

So what is the best way to get the same effect the same output as intended by the above query?

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

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

发布评论

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

评论(3

2024-10-22 12:34:38
select *
from (select * from employee where rownum < some_number and some_id_filter), table2
where some_join_condition and some_other_condition;
select *
from (select * from employee where rownum < some_number and some_id_filter), table2
where some_join_condition and some_other_condition;
温柔戏命师 2024-10-22 12:34:38

这几乎适用于所有数据库,

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

一些数据库具有特殊的语法,可以使这变得更容易。

This will work for nearly all DBs

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

Some DBs have special syntax to make this a little bit eaiser.

宛菡 2024-10-22 12:34:38

我可能没有完全理解您想要完成的任务,但假设您试图将每个员工的行数减少到 1 行,但每个连接都会导致每个员工多行并按员工姓名和其他字段分组仍然不够独特,无法将其缩减为一行,那么您可以尝试使用排名和分区,然后为每个员工分区选择您喜欢的排名。

请参阅示例:http://msdn.microsoft.com/en-us/library/ ms176102.aspx

I may not have a full understanding of what you're trying to accomplish, but lets say you're trying to get it down to 1 row per employee, but each join is causing multiple rows per employee and grouping by employee name and other fields is still not unique enough to get it down to a single row, then you can try using ranking and partitioning and then select the rank you prefer for each employee partition.

See example : http://msdn.microsoft.com/en-us/library/ms176102.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文