SQL选择具有最高计数的行

问题描述 投票:1回答:2

我试图根据两个字段仅选择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。

任何人都知道如何做到这一点?这将不胜感激。

sql sql-server tsql
2个回答
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;

0
投票

我建议一个窗函数:

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
© www.soinside.com 2019 - 2024. All rights reserved.