mysql查询最低选项和

yshpjwxd  于 2021-06-21  发布在  Mysql
关注(0)|答案(6)|浏览(305)

我得到了一个返回以下内容的查询:

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

wvt8vs2t

wvt8vs2t1#

另一种使用分区而不使用 group by 陈述

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

jecbmhm32#

我会用相关性 subquery :

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

wvyml7n53#

您可以执行如下查询

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

0md85ypi4#

其他一些方法是使用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

vdgimpew

vdgimpew5#

可以使用子查询选择 min 每个身份证的价格是多少 sum 这些价值观:

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

j13ufse26#

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

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

相关问题