【问题标题】:How to fetch row having minimum value from sub-query in SQL?如何从 SQL 中的子查询中获取具有最小值的行?
【发布时间】:2020-04-10 09:46:34
【问题描述】:

我有一张表Saledetail,列有prodid, Quantity。我想从该表中获取具有最小数量总和的prodid

在浏览了一些资源后,例如:SQL query to select distinct row with minimum value

我写了这个查询

select prodid, sum(quantity) as k
from saledetail
group by prodid

它的输出是:

+--------+----+
| PRODID | K  |
+--------+----+
|    102 | 11 |
|    101 |  5 |
|    104 |  4 |
|    106 |  4 |
|    103 |  2 |
+--------+----+

现在为了获得具有最小值kprodid,我将不得不使用select min(k) from table_name。但我没有该查询的table_name,因为它是一个子查询。我也试过给它们起别名,然后我得到了错误,无法弄清楚。

我想知道如何完成我的要求?

如果有更好的解决方案也欢迎。

谢谢

【问题讨论】:

  • 为了获得具有最小值 k 的 prodid,我将不得不使用 select min(k) from table_name 只需按 sum 排序并获得第一条记录。
  • 输出输出中的 k 是什么,而这绝不是您的第一个查询的输出。请阅读meta.stackoverflow.com/questions/333952/…
  • @abhishek:如果你得到 ORA-00936,那么你的 DBMS 是 Oracle,而不是 MySQL。这是两个不同的数据库管理系统。您的 Oracle 版本是哪个? (运行SELECT * FROM v$version;)。
  • 好的,我已经更新了答案以展示 Oracle 解决方案。 (这也是标准SQL中的解决方案,即对所有符合这方面标准的DBMS都有效。)
  • 您也可以使用 with 子句。在您的示例中:with sums as (select prodid, sum(quantity) as k from saledetail group by prodid) select * from sums where k = (select min(k) from sums);,这可能是您一直在寻找的。我已将此添加到我的答案中。

标签: sql oracle oracle12c


【解决方案1】:

甲骨文

要获取 Oracle 中总数最少的产品,请使用FETCH FIRST ROWS

select prodid, sum(quantity) as sum_quantity
from saledetail
group by prodid
order by sum(quantity)
fetch first rows with ties;

使用原始查询的替代方法是:

with sums as 
(
  select prodid, sum(quantity) as sum_quantity 
  from saledetail 
  group by prodid
)
select * 
from sums
where sum_quantity = (select min(sum_quantity) from sums);

MySQL

此查询为您提供一种具有最小数量总和的产品:

select prodid, sum(quantity) as sum_quantity
from saledetail
group by prodid
order by sum(quantity)
limit 1;

但是,LIMIT 没有 ties 子句。因此,如果两个或多个产品共享相同的最小总数,则上述查询将任意选择其中一个。

这里是一个简单的查询,可以得到所有个最小数量总和的产品:

select prodid, sum(quantity) as sum_quantity
from saledetail
group by prodid
having sum(quantity) =
(
  select sum(quantity)
  from saledetail
  group by prodid
  order by sum(quantity)
  limit 1
);

从 MySQL 8 开始,您可以使用窗口函数来读取表一次:

select prodid, sum_quantity
from
(
  select 
    prodid,
    sum(quantity) as sum_quantity,
    min(sum(quantity)) over () as min_sum_quantity
  from saledetail
  group by prodid
) aggregated
where sum_quantity = min_sum_quantity;

Oracle 查询和最后一个 MySQL 查询都是标准 SQL。 MySQL 不支持fetch first rows with ties,所以第一个Oracle 查询在MySQL 中不起作用。第二个使用WITH 子句从 MySQL 8 开始工作。

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2018-03-19
    • 2020-03-07
    • 2022-11-25
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多