Reputation: 541
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?
Upvotes: 1
Views: 731
Reputation: 175796
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?
Upvotes: 5