Home > Software design >  How to ignore a varying number of starting 0s in a SQL column for group by
How to ignore a varying number of starting 0s in a SQL column for group by

Time:02-24

I am using the following query to find repeated numbers in my table:

SELECT 
    c.code,
    COUNT(c.code) 
FROM cards c
group by c.code
HAVING COUNT(c.code)>1;

But the column code has varying numbers of 0s before the numbers, as an example:

0001897
001897
01897
1897

How could I make that query ignore all 0s before the numbers to consider all of the above as repeated (the same row in a group by)?

CodePudding user response:

You can try to use TRIM function with LEADING '0'

SELECT 
    TRIM(LEADING '0' FROM c.code),
    COUNT(c.code) 
FROM cards c
group by TRIM(LEADING '0' FROM c.code)
HAVING COUNT(c.code)>1;

SQLFIDDLE

  • Related