我需要給出的形式值的表中的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天起)
我需要給出的形式值的表中的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天起)
以下是可能的解決方案
select id,
length(@k:=concat(day1,day2,day3,day4,day5&&1))
- length(trim(trailing '0' from @k)) as trailing_zeros
from days_table
我採取了蠻力的方法:
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。
但是,是的,我相當肯定你在做什麼,你的方法是次優的。
我會去這樣的事情。當然這假設你只有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
可怕,是不是?
的靈感來自於一個版本@YaroslavPogrebnyak的回答
NULL
安全(萬一列可以爲空)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演示
在867820天,是名爲'day867820'列? [數據庫規範化](http://en.wikipedia.org/wiki/Database_normalization) – Kermit
您正在使用哪些DBMS? SQL代表結構化查詢語言。 – Kermit
對不起,它的mysql。是的列名是那種形式 – user1893354