将内部联接查询的结果限制为2行

时间:2019-06-19 22:29:56

标签: sql sql-server having-clause

我的查询给我分组数据的结果,但现在我只需要两行

我已经尝试过HAVING COUNT(*) <= 2,但是问题在选择列表中无效,因为它没有包含在聚合函数或GROUP BY子句中。

我的查询是

select f.CompanyName, f.EmployeeCity, f.PrioritySL ,f.EmployeeSeniorityLevel ,f.EmployeeID
from (
   select ConcatKey, min(PrioritySL) as PSL 
   from dbo.WalkerItContacts group by ConcatKey 
) as x inner join dbo.WalkerItContacts as f on f.ConcatKey = x.ConcatKey and f.PrioritySL = x.PSL
where f.PrioritySL != '10'

公司苹果有9条记录,我只想要2条记录

我的数据

company name priority a 10 a 1 a 3 b 2 b 4 b 3 b 5 c 1 c 10 c 2

我的预期数据

company name priority a 1 a 3 b 2 b 3 c 1 c 2

3 个答案:

答案 0 :(得分:0)

在外部查询中添加“ top 2”子句:

select top 2 f.CompanyName, f.EmployeeCity, f.PrioritySL ,f.EmployeeSeniorityLevel ,f.EmployeeID
    from (
       select ConcatKey, min(PrioritySL) as PSL 
       from dbo.WalkerItContacts group by ConcatKey 
    ) as x inner join dbo.WalkerItContacts as f on f.ConcatKey = x.ConcatKey and f.PrioritySL = x.PSL
    where f.PrioritySL != '10' 
and f.CompanyName= 'Apple'

将给您两行。在外部查询中添加一个order子句,以便您可以控制返回哪两行。

答案 1 :(得分:0)

您可以更简洁地表达此短语,并具有以下更好的性能:

select top (2) wic.*
from (select wic,
             rank() over (partition by CompanyName, ConcatKey order by PrioritySL) as seqnum
      from dbo.WalkerItContacts wic
     ) wic
where seqnum = 1 and
      wic.PrioritySL <> 10 and
      wic.CompanyName = 'Apple';

答案 2 :(得分:0)

我认为您可以使用ROW_NUMBER()函数对行进行计数并在WHERE子句中对其进行过滤以仅每组显示2行来解决您的问题。

我认为类似这样的方法可能对您有用:

True

希望这对您有所帮助。