显示每个卖家的最大销售额的查询

1yjd4xko  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(385)

我有一张这样的table(示例):

Name_Seller   Month   Value
---------------------------
Seller A      Jan     200
Seller B      Jan     100
Seller A      Fev     300
Seller B      Fev     100
Seller C      Jan     400
Seller A      Mar     200
Seller D      Jan     300

sql查询:

SELECT Name_Seller, Month, Value 
FROM SALES
WHERE Value = (SELECT MAX(Value) FROM SALES GROUP BY Name_Seller);

我想为每一个卖家打印出他最大的销售额和销售时间。
你能帮我修正我的问题并解释为什么它不起作用吗?
我试过:

select name_seller, month, max(value) 
from sales 
group by name_seller, month;

但是这个查询返回:

+---------------+------------+------+
| NAME_SELLER   | MAX(VALUE) | MONTH|
+---------------+------------+------+
| SELLER A      |    4182.00 | Jan  |
| SELLER A      |    3261.00 | Fev  |
| SELLER A      |    4219.00 | Mar  |
| SELLER B      |    2123.00 | Jan  |
| SELLER B      |    2111.00 | Fev  |
| SELLER B      |    3918.00 | Mar  |
| SELLER C      |    3000.00 | Jan  |
| SELLER C      |    4000.00 | Fev  |
| SELLER C      |    1500.00 | Mar  |
| SELLER D      |    2819.00 | Jan  |
| SELLER D      |    3881.00 | Fev  |
| SELLER D      |    2012.00 | Mar  |
+---------------+------------+------+

我想要每个销售员的最高销售额和销售时间。
因此,它应该只返回一个销售人员为每个销售。

ruarlubt

ruarlubt1#

ROW_NUMBER() 窗口功能:

SELECT t.Name_Seller, t.Month, t.Value
FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Name_Seller ORDER BY Value DESC) rn
  FROM SALES
) t
WHERE t.rn = 1

改变 ROW_NUMBER()RANK() 如果你想要回领带。
或者在 WHERE 条款:

SELECT s.* FROM SALES s
WHERE s.Value = (SELECT MAX(VALUE) FROM SALES WHERE Name_Seller = s.Name_Seller)

或者如果您的数据库支持:

SELECT * FROM SALES
WHERE (Name_Seller, Value) IN (SELECT Name_Seller, MAX(VALUE) FROM SALES GROUP BY Name_Seller)
whhtz7ly

whhtz7ly2#

您的查询也可以带来结果,但是where子句中的“=”运算符需要更改为“in”,因为下面的查询带来了不止一行,所以它需要where子句中的in运算符。此外,查询中的数据返回了正确的结果,但请注意一般情况下使用,因为与@forpas给出的示例中的销售金额(值)进行比较也会产生错误的结果。

更改运算符后,您的查询将工作。

SELECT Name_Seller, Month, Value FROM SALES
 WHERE Value IN (Select MAX(Value) FROM SALES GROUP BY Name_Seller);

也可以使用rank()窗口函数

SELECT Name_Seller, Month, VALUE
 FROM (SELECT Name_Seller, Month, VALUE,
       RANK() OVER (PARTITION BY Name_Seller ORDER BY VALUE DESC ) as RN
       FROM SALES
      ) A
 WHERE A.RN = 1

m1m5dgzv

m1m5dgzv3#

它看起来是这样的:

SELECT Name_Seller, Month, MAX(Value)
FROM SALES
GROUP BY Name_Seller, Month;
zaq34kh6

zaq34kh64#

您可以使用下面的查询,

select name_seller, month, max(value) from sales group by name_seller, month;

如果你也期待一个月,那么使用,

select s2.name_seller, s1.month, max(s2.value) from sales s1
inner join 
(select name_seller, max(value) as value from sales
group by name_seller) s2
on (s1.name_seller = s2.name_seller and s1.value = s2.value);

相关问题