简体   繁体   中英

How to get minimum value of a particular record column in SQL?

Sql/Mysql

select * from test;

fare_str = varchar(100) datatype.

+-----------------+-------------+-------------+
| 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 |
+-----------------+-------------+-------------+

required output: Here how can i get min value of a particular raw and column fare_str by sql query;

+-----------------+-------------+-------------+
| 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 |
+-----------------+-------------+-------------+

Try this

    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  

Use Substring_Index, if min value is at first. Query for the same

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

If min values are in between, then refer this thread :

"Reverse GROUP_CONCAT" in MySQL?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM