In SQL I have a table with 3 columns:
| Month1 | Month2 | Month3 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 1 | 1 |
| 0 | 1 | 1 |
...and so on.
I need another column where it gives the mode of Month1, Month2 and Month3.
My expected output is:
| Month1 | Month2 | Month3 | Mode |
|---|---|---|---|
| 0 | 1 | 0 | 0 |
| 1 | 1 | 1 | 1 |
| 0 | 1 | 1 | 1 |
So far I have only calculated mode for a single column. Not sure how we can do it horizontally by combining 3 columns.
This should work, can easily be expanded for n columns:
For RDBMS other than SQL server, replace
values(...)with appropriate table value constructor,cross applywith lateral join/sub query inside select andtop 1with limit/offset...fetch.