简体   繁体   中英

How to get distinct records but on base on first 2 digits only in MySQL

I want to get distinct records (only one field) from a MySQL table, and that field contain only digits.

Example:

00010000
01111100
01112000
01118000
02301201

But distinct records is considered on base on first 2 digits. So in the case above, I need to get back only 3 records:

00010000
01112000
02301201

More over, I would like to trim the rest of the digits, so the actual end result should be:

00
01 
02

So distinct and group by will not cut here. Any idea?

Assuming you wanted the least value from among duplicates, you could try:

SELECT t1.col
FROM yourTable t1
INNER JOIN
(
    SELECT LEFT(col, 2) AS prefix, MIN(col) AS min_col
    FROM yourTable
    GROUP BY LEFT(col, 2)
) t2
    ON LEFT(t1.col, 2) = t2.prefix AND
       t1.col = t2.min_col;

Note: Numbers in MySQL don't start with zeroes, so your requirement (and this answer) only make sense if your column is text.

DISTINCT will work fine with LEFT to give the results you want:

SELECT DISTINCT(LEFT(value, 2)) AS value
FROM data
ORDER BY value 

Output

00
01
02

Demo on dbfiddle

If you only want the trimmed value, try this:

SELECT SUBSTRING(yourColumn,1,2) as trimmedval
FROM Table
GROUP BY SUBSTRING(yourColumn,1,2)

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