mysql查询最低选项总和

时间:2018-06-12 15:37:14

标签: mysql sql

我有一个返回以下内容的查询:

ID | Price
---------------
1 | 20
1 | 30
1 | 15
2 | 10
2 | 12
2 | 20
3 | 1
3 | 0
3 | 0
4 | 0
4 | 0 
4 | 7

我想知道是否有办法可以获得每个ID的最低值之和。所以在这种情况下,它将返回25。 15 + 10 + 0 + 0

6 个答案:

答案 0 :(得分:2)

您可以使用子查询为每个ID选择min价格,然后sum这些值:

select sum(minprice) as overallprice
from (
    select min(price) minprice
    from yourtable
    group by id) t

答案 1 :(得分:0)

您可以创建一个子查询,查找每个ID的最低价格,并从中获取结果并将它们相加。在伪代码中:

select
  sum(lowest_price)
from (select id, min(price) as lowest_price from prices group by id) lowest_prices

答案 2 :(得分:0)

您可以执行以下查询

 Select sum (a) from
  (
     Select min (price) as a from yourtable
    Group by id
 ) t

答案 3 :(得分:0)

使用分区而不使用group by语句的另一种方法

select sum(price.min_price) from 
(select distinct id,min(price) over(partition by id) as min_price from prices) price

答案 4 :(得分:0)

其他一些方法是使用MySQL用户变量或自我左连接..

MySQL用户变量解决方案

<强>查询

SELECT 
 SUM(prices.Price)
FROM ( 
  SELECT 
     prices.Price
   , CASE 
       WHEN @id != prices.id    
       THEN 1
       ELSE 0 
     END AS isMinGroupValue
   , (@id := prices.id)    
  FROM 
    prices 
  CROSS JOIN (
    SELECT 
      @id := 0
   ) AS init_user_params
  ORDER BY
     prices.ID ASC
   , prices.price ASC 
) AS prices
WHERE
  prices.isMinGroupValue = 1 

参见演示https://www.db-fiddle.com/f/nzWqMQAxd7mvq589R7WuZ8/0

自我左加入解决方案

<强>查询

SELECT 
 SUM(prices1.Price)
FROM 
 prices prices1
LEFT JOIN
 prices prices2
ON
   prices1.ID = prices2.ID
 AND
   prices1.price > prices2.price
WHERE
 prices2.ID IS NULL

参见演示https://www.db-fiddle.com/f/nzWqMQAxd7mvq589R7WuZ8/1

答案 5 :(得分:0)

我会使用 correlation subquery

select sum(t.price) as overallprice
from table t
where price = (select min(price) from table t1 where t1.id = t.id);