获取产品计数,不包括该产品在sql中的最大值

vcirk6k6  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(227)
1.   Product A   7.5
   2.   Product A   7.3
   3.   Product A   7.4
   4.   Product B   6.2
   5.   Product B   6.5
   6.   Product B   6.01
   7.   Product c   2.4
   8.   Product c   2.0

不包括产品a=7.5的最大值行,则该产品a的剩余计数将为2。所以我需要

Product A  2
Product B  2
Product C  1..
bttbmeg0

bttbmeg01#

您可能有具有相同最大值的重复项。如果是:

select t.product
from t join
     (select product, max(price) as maxprice
      from t
      group by product
     ) tt
     on t.product = tt.product
where t.price < t.maxprice
group by t.product;
rta7y2nd

rta7y2nd2#

如果最大值没有重复项,则只需从计数中减去1:

SELECT product, COUNT(*) - 1 AS counter FROM products GROUP BY product;

如果有重复的,你想把它们都排除在外:

SELECT p.product, COUNT(*) AS counter 
FROM products p 
WHERE p.value < (SELECT MAX(value) FROM products WHERE product = p.product) 
GROUP BY p.product;

或者如果要返回零:

SELECT 
  p.product, 
  COUNT(*) - (
    SELECT COUNT(*) 
    FROM products 
    WHERE 
      product = p.product 
      AND 
      value = (
        SELECT MAX(value) FROM products WHERE product = p.product
      )
  ) AS counter 
FROM products p 
GROUP BY p.product;

相关问题