简体   繁体   中英

Query to split even and odd numbers, with GROUP_CONCAT

I have a query that finds housenumbers per street in a specific postcode with four numbers:

SELECT *,
    GROUP_CONCAT(DISTINCT CAST(housenumber AS int) ORDER BY housenumber ASC) AS housenumbers
FROM streets
WHERE postcode LIKE '3031%'
GROUP BY street
ORDER BY lat,lon

This is the result of the groupcatted housenumbers.

491,492,493,500,501,502,503,504,505,506,507,508,50

I would like to split the result, over two columns, in evenhousenumber and oddhousenumbers. I tried MOD and %2 , but both require a WHERE and it's not possible to use the WHERE in the groupcat function, I noticed.

How can I split the result, over even and odd numbers?

You could use CASE expression:

SELECT street
 ,GROUP_CONCAT(DISTINCT CASE WHEN MOD(CAST(housenumber AS int),2) = 0 THEN CAST(housenumber AS int) END ORDER BY housenumber ASC) AS housenumbers_even
 ,GROUP_CONCAT(DISTINCT CASE WHEN MOD(CAST(housenumber AS int),2) = 1 THEN CAST(housenumber AS int) END ORDER BY housenumber ASC) AS housenumbers_odd
FROM streets
WHERE postcode LIKE '3031%'
GROUP BY street
ORDER BY lat,lon;

It works because GROUP_CONCAT skips NULL values.


Also SELECT * ... GROUP BY street is not safe. Related: Group by clause in mySQL and postgreSQL, why the error in postgreSQL?

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