如何在SQL中获取特定记录列的最小值?

时间:2014-06-25 10:49:06

标签: mysql sql

SQL / Mysql的

从测试中选择*;

fare_str = varchar(100)数据类型。

+-----------------+-------------+-------------+
| fare_str        | operator_id | bus_type_id |
+-----------------+-------------+-------------+
| 550,600,555     |           7 |          62 |
| 650,660         |           2 |          77 |
| 449,449,449,449 |           4 |          77 |
| 333             |          21 |          75 |
| 650             |           7 |          50 |
| 500             |           2 |          97 |
+-----------------+-------------+-------------+

所需输出: 这里我如何通过sql查询得到特定原始和列fare_str的最小值;

+-----------------+-------------+-------------+
| fare_str        | operator_id | bus_type_id |
+-----------------+-------------+-------------+
| 550             |           7 |          62 |
| 650             |           2 |          77 |
| 449             |           4 |          77 |
| 333             |          21 |          75 |
| 650             |           7 |          50 |
| 500             |           2 |          97 |
+-----------------+-------------+-------------+

2 个答案:

答案 0 :(得分:0)

试试这个

    SELECT MIN(SUBSTRING_INDEX(SUBSTRING_INDEX(t.fare_str, ',', n.n), ',', -1)) value,operator_id, bus_type_id  
    FROM Table1 t CROSS JOIN 
      (
       SELECT a.N + b.N * 10 + 1 n
       FROM 
          (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
         ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
       ORDER BY n 
       ) n
    WHERE n.n <= 1 + (LENGTH(t.fare_str) - LENGTH(REPLACE(t.fare_str, ',', '')))
    Group By operator_id, bus_type_id  

答案 1 :(得分:0)

如果最初是最小值,请使用Substring_Index。查询相同的

SELECT Substring_Index(fare_str,',' ,1), operator_id, bus_type_id  from test

如果介于最小值之间,请参考此主题:

"Reverse GROUP_CONCAT" in MySQL?