SQL选择具有最高计数的行

时间:2018-03-06 11:40:19

标签: sql sql-server tsql

我尝试根据两个字段仅选择COUNT()最高的行。

首先,我有一个查询,它给出了我的表中特定ITEM-SUPPLIER组合发生了多少次的值。

select itemid, ordersupplierid, COUNT(OrderSupplierId) AS SupCount from purchaseorderline
group by itemid, ordersupplierid
order by ItemID

在结果中我有:

itemid   | ordersupplierid | SupCount
15850    |  579            |  1
15850    |  587            |  3
15850    |  605            |  2
15851    |  616            |  5
15852    |  579            |  1
15852    |  587            |  2
15854    |  616            |  11
15855    |  616            |  1

所以从那里我只需要获得行:

itemid   | ordersupplierid | SupCount
15850    |  587            |  3
15851    |  616            |  5
15852    |  587            |  2
15854    |  616            |  11
15855    |  616            |  1

与ItemId - OrderSupplierId组合,具有最高的SupCount。

任何人都知道如何做到这一点?非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用窗口功能:

select itemid, ordersupplierid, supcount
from (select itemid, ordersupplierid, count(*) AS SupCount,
             max(count(*)) over (partition by itemid) as maxcount
      from purchaseorderline
      group by itemid, ordersupplierid
     ) io
where supcount = maxcount
order by ItemID;

如果有联系,那么这将返回所有匹配的行。如果您只想要一行(即使有关系),那么您可以使用row_number()

select itemid, ordersupplierid, supcount
from (select itemid, ordersupplierid, count(*) AS SupCount,
             row_number() over (partition by itemid order by count(*) desc) as seqnum
      from purchaseorderline
      group by itemid, ordersupplierid
     ) io
where seqnum = 1
order by ItemID;

答案 1 :(得分:0)

I would suggest a Window Function:

WITH cte AS(
  select itemid, ordersupplierid, COUNT(OrderSupplierId) AS SupCount
  from purchaseorderline
  group by itemid, ordersupplierid
  order by ItemID
),
cteFilter AS(
SELECT itemid, ordersupplierid, SupCount, ROW_NUMBER() OVER (PARTITION BY itemid ORDER BY SupCount DESC) rn
  FROM cte
)
SELECT itemid, ordersupplierid, SupCount
  FROM cteFilter
  WHERE rn = 1