MySQL查询分组并使用不同的行

时间:2013-06-13 19:34:57

标签: mysql sql distinct

我有一个格式如下的表:

 mysql> select pattern,trunks,cost from sms_prices where pattern=1;
 +---------+--------------+-------+
 | pattern | trunks       | cost  |
 +---------+--------------+-------+
 | 1       | Vitelity     | 0.099 |
 | 1       | Plivo        | 0.012 |
 | 1       | Twilio       | 0.012 |
 +---------+--------------+-------+
 3 rows in set (0.00 sec)

我的问题是:

考虑到这个表有另外700多个条目,相同模式有3-4个条目,如何按成本,ASC选择DISTINCT(模式)排序?

我试过了:

 mysql> select DISTINCT pattern,cost,trunks from sms_prices where pattern=1 order by cost;
 +---------+-------+--------------+
 | pattern | cost  | trunks       |
 +---------+-------+--------------+
 | 1       | 0.012 | Plivo        |
 | 1       | 0.012 | Twilio       |
 | 1       | 0.099 | Vitelity     |
 +---------+-------+--------------+
 3 rows in set (0.00 sec)

 mysql>

但是你可以看到它仍然给了我相同的3个结果。

如果我只选择一个DISTINCT行,它会给我一个条目:

 mysql> select DISTINCT pattern from sms_prices where pattern=1 order by cost;
 +---------+
 | pattern |
 +---------+
 | 1       |
 +---------+
 1 row in set (0.00 sec)

但我不知道这是哪个条目,所以结果没用。

请帮助查看每pattern次返回单个结果的查询,cost

谢谢!

3 个答案:

答案 0 :(得分:1)

也许这可能不是你想要的,但是:

SELECT pattern, cost, trunks 
FROM sms_prices 
WHERE cost = (select min(cost) from sms_prices where pattern = 1)
GROUP BY pattern;

此致

答案 1 :(得分:0)

这不会起作用吗?

select pattern, min(cost) mincost
from sms_prices 
where whatever
group by pattern

答案 2 :(得分:0)

SELECT模式,成本,中继FROM sms_prices AS OT WHERE cost =(从sms_prices选择min(cost)作为IT,其中OT.pattern = IT.pattern)GROUP BY模式;