SQL查询以查找跨列的尾随零数

时间:2013-10-07 19:15:56

标签: mysql sql

我需要一个sql查询,它给出了表格

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

给出

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

,即每个id的日期列中的连续尾随零的数量(从第5天开始)

4 个答案:

答案 0 :(得分:3)

我会选择这样的东西。当然这假设你只有5天:

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

太可怕了,不是吗?

答案 1 :(得分:2)

这是可能的解决方案

select id,
   length(@k:=concat(day1,day2,day3,day4,day5&&1)) 
    - length(trim(trailing '0' from @k)) as trailing_zeros 
from days_table

答案 2 :(得分:1)

我采取了蛮力方法:

CREATE TABLE #temp (id int, day1 int, day2 int, day3 int, day4 int, day5 int)
INSERT INTO #temp (id,day1,day2,day3,day4,day5) VALUES (1,4,0,5,0,0),(2,2,0,0,0,0)

SELECT id,
    CASE 
        WHEN day5=0 AND day4=0 AND day3=0 AND day2=0 AND day1=0 THEN 5
        WHEN day5=0 AND day4=0 AND day3=0 AND day2=0 THEN 4
        WHEN day5=0 AND day4=0 AND day3=0 THEN 3
        WHEN day5=0 AND day4=0 THEN 2
        WHEN day5=0 THEN 1
        ELSE 0
        END AS ConsecutiveTrailingZeros
FROM #temp

当然,如果您需要将100计为连续2个零,则此方法会中断。这是SQL Server语法。可能需要调整MySQL。

但是,我相当肯定无论你做什么,你的方法都是次优的。

答案 3 :(得分:0)

受@YaroslavPogrebnyak回答启发的版本

  1. NULL安全(如果列可以为空)
  2. 如果值本身有尾随零(例如10,20,300等),它不会中断。
  3. 它不使用用户(会话)变量
  4. SELECT id, CHAR_LENGTH(
                 SUBSTRING_INDEX(
                   CONCAT(day1<=>0, 
                          day2<=>0, 
                          day3<=>0, 
                          day4<=>0, 
                          day5<=>0),
                   '0', -1)
               ) trailing_zeros
      FROM table1
    

    让我们试一试:

    mysql> CREATE TABLE table1 (id int, day1 int, day2 int, day3 int, day4 int, day5 int);
    Query OK, 0 rows affected (0.05 sec)
    
    mysql> INSERT INTO table1 (id, day1, day2, day3, day4, day5) VALUES
        -> (1, 4, 0, 5, 0, 0),
        -> (2, 2, 0, 0, 0, 0),
        -> (3, 0, 1, 10, 100, 1000),
        -> (4, 2, NULL, 0, 0, 0);
    Query OK, 4 rows affected (0.01 sec)
    Records: 4  Duplicates: 0  Warnings: 0
    
    mysql> SELECT id, CHAR_LENGTH(
        ->              SUBSTRING_INDEX(
        ->                CONCAT(day1<=>0, 
        ->                       day2<=>0, 
        ->                       day3<=>0, 
        ->                       day4<=>0, 
        ->                       day5<=>0),
        ->                '0', -1)
        ->            ) trailing_zeros
        ->   FROM table1;
    +------+----------------+
    | id   | trailing_zeros |
    +------+----------------+
    |    1 |              2 |
    |    2 |              4 |
    |    3 |              0 |
    |    4 |              3 |
    +------+----------------+
    4 rows in set (0.01 sec)
    

    这是 SQLFiddle 演示