SQL 查询限制具有不同值的行数
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这几乎适用于所有数据库,
一些数据库具有特殊的语法,可以使这变得更容易。
This will work for nearly all DBs
Some DBs have special syntax to make this a little bit eaiser.
我可能没有完全理解您想要完成的任务,但假设您试图将每个员工的行数减少到 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