gpt4 book ai didi

mysql - 如何计算一列中分隔值之间重复值的数量并将该值存储在另一个表中

转载 作者:行者123 更新时间:2023-11-29 18:32:51 25 4
gpt4 key购买 nike

我有一个包含两列(id3 和 COL 1)的表(cor)。id3 是自动增量。COL 1包含A/0/1 3种类型的值。

这些值遵循严格的规则。A 之后可以跟 0 或 1。0 后面只能跟 A。1 后面只能跟 1 或 0。

看起来像这样:

id3    | COL 1------ | ------   1    |  A  2    |  1       3    |  1       4    |  0  5    |  A  6    |  0  7    |  A     8    |  1  9    |  0 10    |  A

What I want is the number of 1s in a row between two A for the entire column stored in a second table (garb). The end result should look like this:

  Val  ------   2   0   1

My approach so far was to copy only the values which repeat after each other into the new table.For that I used this code:

INSERT INTO garb (ida2)  SELECT id3  FROM cor;

INSERT INTO garb (ida) SELECT Id3 from cor a1 where 0 < (select count(*) from cor a2 where a2.Id3 = a1.Id3 + 1 and a2.`COL 1` = a1.`COL 1`);

现在我有了重复 1 的 id。我还知道 2 数字中断时下一次重复开始。

但是如何计算并保存每个 A 之间的重复次数呢?或者如果有更简单的解决方案也可以。

提前致谢,布赖恩

最佳答案

一个选项可以是(小心性能问题):

mysql> DROP TABLE IF EXISTS `garb`, `cor`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `garb` (
-> `ida` BIGINT UNSIGNED NOT NULL
-> );
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE IF NOT EXISTS `cor` (
-> `id3` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `COL 1` CHAR(1),
-> KEY (`COL 1`)
-> );
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO `cor`
-> (`COL 1`)
-> VALUES
-> ('A'), ('1'), ('1'), ('0'),
-> ('A'), ('0'), ('A'), ('1'),
-> ('0'), ('A');
Query OK, 10 rows affected (0.00 sec)
Records: 10 Duplicates: 0 Warnings: 0

mysql> INSERT INTO `garb`
-> SELECT SUM(IF(`cor`.`COL 1` = '1', 1, 0)) `Val`
-> FROM (
-> SELECT
-> `cor_out`.`id3` `min`,
-> (SELECT `cor_in`.`id3`
-> FROM `cor` `cor_in`
-> WHERE `cor_in`.`id3` > `cor_out`.`id3` AND
-> `cor_in`.`COL 1` = 'A'
-> LIMIT 1) `max`
-> FROM `cor` `cor_out`
-> WHERE `cor_out`.`COL 1` = 'A'
-> ) `der`
-> INNER JOIN `cor` ON `cor`.`id3`
-> BETWEEN `der`.`min` AND
-> `der`.`max` AND
-> `cor`.`COL 1` != 'A'
-> WHERE `der`.`max` IS NOT NULL
-> GROUP BY `der`.`min`, `der`.`max`;
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> SELECT `ida`
-> FROM `garb`;
+-----+
| ida |
+-----+
| 2 |
| 0 |
| 1 |
+-----+
3 rows in set (0.00 sec)

参见db-fiddle .

关于mysql - 如何计算一列中分隔值之间重复值的数量并将该值存储在另一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45546935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com