3

我需要一个给定表格值表的 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

4 回答 4

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

太可怕了,不是吗?

于 2013-10-07T19:59:21.343 回答
2

这是可能的解决方案

select id,
   length(@k:=concat(day1,day2,day3,day4,day5&&1)) 
    - length(trim(trailing '0' from @k)) as trailing_zeros 
from days_table
于 2013-10-07T19:38:30.007 回答
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 进行调整。

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

于 2013-10-07T19:30:08.623 回答
0

受@YaroslavPogrebnyak 回答启发的版本

  1. 它是NULL安全的(如果有任何机会列可以为空)
  2. 如果值本身有尾随零(例如 10、20、300 等),它不会中断
  3. 它不使用用户(会话)变量
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演示

于 2013-12-19T08:43:33.920 回答