Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to find number of trailing zeros across columns

Tags:

sql

mysql

I need an sql query that given table of values of the form

| id | day1 | day2 | day3 | day4 | day5 |
| 1  |  4   |  0   |  5   | 0    | 0    |
| 2  |  2   |  0   |  0   | 0    | 0    |

gives

| id | trailing_zeros |
| 1  | 2              |
| 2  | 4              |

that is, the number of consecutive trailing zeros in the days columns for each id (from day5 backwards)

like image 510
user1893354 Avatar asked Nov 23 '25 05:11

user1893354


2 Answers

I'd go for something like this. Of course this is assuming you only have 5 days:

SELECT
  id,
  CASE WHEN day5 = 0 THEN
    CASE WHEN day4 = 0 THEN
      CASE WHEN day3 = 0 THEN
        CASE WHEN day2 = 0 THEN
          CASE WHEN day1 = 0 THEN 5
          ELSE 4 END
        ELSE 3 END
      ELSE 2 END
    ELSE 1 END
  ELSE 0 END
  amount_of_zeros
FROM t

Awful, isn't it?

like image 67
Mosty Mostacho Avatar answered Nov 25 '25 18:11

Mosty Mostacho


Here is possible solution

select id,
   length(@k:=concat(day1,day2,day3,day4,day5&&1)) 
    - length(trim(trailing '0' from @k)) as trailing_zeros 
from days_table
like image 21
Yaroslav Pogrebnyak Avatar answered Nov 25 '25 20:11

Yaroslav Pogrebnyak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!