Skip to content
Advertisement

Group numbers by 45 in mysql

I have a database in which I store wind direction readings by degrees. I need to do two things really, i need to group all readings by 45 (basically 45 degrees between “N”, “NE”, “E”, “SE”, “S”,”SW”,”W” and “NW”) and then i need to find the percentage of each of those groups in all readings.

This is where i’m stuck so far, i have managed only to group by reading_direction (missing the part how to group by 45) and managed to display percentage.

This is my fiddle: MySql

In last 30ish minutes i have managed to figure out how to gorup by number ranges so this is half of my problem done:

I just need to find what is the percentage of all groups in count(*)

Advertisement

Answer

One easy solution would to divide reading_winddirection by 45, keep the integer part only, and use this for grouping.

Note: if you are using MySQL 8.0, you can use window functions instead of joining to compute the total count:

In this db fiddle, both queries yield:

windgroup | cnt | postotak
:-------- | --: | -------:
N         |   6 |       60
E         |   2 |       20
SE        |   1 |       10
SW        |   1 |       10
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement