繁体   English   中英

“具有条款”中的未知列“a.revenue”

[英]Unknown column 'a.revenue' in 'having clause'

SELECT 
      a.seller_id seller_id
FROM 
     (SELECT seller_id, sum(price) revenue 
      FROM Sales GROUP BY seller_id) as a
HAVING 
     a.revenue = min(a.revenue)

我得到的错误是Unknown column 'a.revenue' in 'having clause'我想获得收入最低的卖家。 好像我既不能使用wherehaving 我该怎么办?

下面是表结构,列名“价格”实际上是每个产品的收入。

+-----------+------------+----------+------------+----------+-------+
| seller_id | product_id | buyer_id | sale_date  | quantity | price |
+-----------+------------+----------+------------+----------+-------+
| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
| 2         | 2          | 3        | 2019-06-02 | 1        | 800   |
| 3         | 3          | 4        | 2019-05-13 | 2        | 2800  |
+-----------+------------+----------+------------+----------+-------+

预期的输出是

+-------------+
| seller_id   |
+-------------+
| 2           |
+-------------+

您需要做的是首先在子查询中计算最小收入,并使用它来检查所有卖家的收入等于最低收入。

像这样的东西

select 
  seller_id,sum(price) 
from sales 
group by seller_id 
having sum(price) = (select sum(price) from sales group by seller_id order by 1 limit 1)

revenue仅在子查询中可用。 您需要将它“导出”到外部查询的结果,以便外​​部查询的HAVING可以访问它。

SELECT 
      a.seller_id seller_id, a.revenue revenue ...

现在我无法测试它但是,我认为这样的事情可以工作

Select * from (
SELECT a.seller_id seller_id FROM (SELECT seller_id, sum(price) revenue FROM Sales) as a) as res GROUP BY res.seller_id  having res.revenue = min(res.revenue) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM