简体   繁体   中英

Select the largest number from MYSQL Table with added Prefix

I have a table that unfortunately, I can't alter in any way and have to work with what I have.

The mysql table has a field labeled, "customer_id". It has 2 prefixed letters with a 4-value numerical number.

EX: BI8392

HE8492

WO1293

How can I select the largest numerical value with a certain prefix? For example, assume that I wanted to select the largest number with a prefix of HE. How can I select that value?

Any help is absolutely appreciated. I've been stuck for a while now.

Since all values left padded you can do

SELECT RIGHT(MAX(customer_id), 4) max_val
  FROM table1
 WHERE customer_id LIKE 'HE%'

Make sure that you have an index on customer_id which you probably do based on a name of the column. LIKE will most likely use it.

Here is SQLFiddle demo

SELECT LEFT(customer_id,2) AS PREFIX,
       MAX(RIGHT(customer_id,4)) AS MAX
FROM table1
GROUP BY LEFT(customer_id,2)

SQL Fiddle

MySQL 5.5.32 Schema Setup :

CREATE TABLE Table1
    (`customer_id` varchar(6))
;

INSERT INTO Table1
    (`customer_id`)
VALUES
    ('DD1234'),
    ('DD1222'),
    ('EE2345'),
    ('EE6789')
;

Query 1 :

SELECT LEFT(customer_id,2) AS PREFIX,
       MAX(RIGHT(customer_id,4)) AS MAX
FROM table1
GROUP BY LEFT(customer_id,2)

Results :

| PREFIX |  MAX |
|--------|------|
|     DD | 1234 |
|     EE | 6789 |

EDIT :

SELECT MAX(RIGHT(customer_id,4)) AS MAX
FROM table1
GROUP BY LEFT(customer_id,2)
WHERE LEFT(customer_id,2) = 'HE'

USE:

SELECT MAX(RIGHT(customer_id,4)) AS max fROM table_name 
    WHERE LEFT(customer_id,2)='HE'; 

If your prefixes have the same length, you could do:

Ex.

SELECT MID(column_name,start[,length]) FROM table_name;

Filled out:

SELECT MID(customer_id,2,4) FROM table_name;

Sample data:

mysql> SELECT * FROM Document;
+--------+-------------+
| DataID | Description |
+--------+-------------+
|      1 | BI8392      |
|      2 | HE8492      |
|      3 | HE8493      |
|      4 | HE8490      |
+--------+-------------+

Query:

SELECT MAX(SUBSTR(Description,3)) FROM Document
WHERE SUBSTR(Description,1,2) = 'HE';

Returns:

+----------------------------+
| MAX(SUBSTR(Description,3)) |
+----------------------------+
| 8493                       |
+----------------------------+

In SQL Server, you can do a substring and then to ORDER BY, you will need to cast it to a decimal (else it will order by Varchar, Example 999 will be greater than 1000)

  SELECT SUBSTRING(MyColumn,3, LEN(MyColumn) - 2 ) 
  FROM dbo.MyTable
  ORDER BY CAST(SUBSTRING(MyColumn,3, LEN(MyColumn) - 2 ) as decimal) DESC;

The number 3 above is if the Prefix is 2 characters long. Consequently, the number 2 is to find the length of string without Prefix.

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