如何统计值组合的累计出现次数

How to count the cumulative occurrence of a value combination

(我对数据库编程很陌生,请原谅一个可能很原始的问题。) 我有一个 MySQL table:

id value1 value2
----------------
1  1      A 
2  1      B
3  2      A
4  3      A
5  3      A
6  3      B
7  3      A

我想创建另一个值 OCCURRENCE,它等于迄今为止在 table 中找到 VALUE1 VALUE2 的特定组合的次数。定义 "until now" 的顺序根据 id 列:

id value1 value2 occurrence
---------------------------
1  1      A      1
2  1      B      1
3  2      A      1
4  3      A      1
5  3      A      2
6  3      B      1
7  3      A      3

我该怎么做?

您最好将此作为计数而不是 table 中的存储值。

SELECT value1, value2, COUNT(*) 
FROM TABLE
GROUP BY value1, value2

你可以在mysql中模仿row_number函数如下

SELECT a.value1, a.value2, (
SELECT count(*) from table b where a.value1 >= b.value2 AND a.value1 = b.value1) AS occurrence 
FROM table a

这是一种方法,尽管这种方法的扩展性不是特别好...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,value1 INT NOT NULL
,value2 CHAR(1) NOT NULL
);

INSERT INTO my_table VALUES
(1,1,'A'),
(2,1,'B'),
(3,2,'A'),
(4,3,'A'),
(5,3,'A'),
(6,3,'B'),
(7,3,'A');

SELECT x.*
     , COUNT(y.id) rt
  FROM my_table x
  JOIN my_table y
    ON y.value1 = x.value1
   AND y.value2 = x.value2
   AND y.id <= x.id
 GROUP
    BY x.id;

+----+--------+--------+----+
| id | value1 | value2 | rt |
+----+--------+--------+----+
|  1 |      1 | A      |  1 |
|  2 |      1 | B      |  1 |
|  3 |      2 | A      |  1 |
|  4 |      3 | A      |  1 |
|  5 |      3 | A      |  2 |
|  6 |      3 | B      |  1 |
|  7 |      3 | A      |  3 |
+----+--------+--------+----+

...这是一个更快的方法...

SET NAMES utf8;

SELECT x.id
     , value1
     , value2
     , x.n
  FROM 
     ( SELECT id
            , CASE WHEN value1 = @prev1 AND value2 = @prev2 THEN @i:=@i+1 ELSE @i:=1 END n
            , @prev1:=value1 value1
            , @prev2:=value2 value2 
         FROM my_table
            , (SELECT @i:=1, @prev1:=0,@prev2:='') vars 
        ORDER 
           BY value1
            , value2
     ) x
 ORDER 
    BY id;

+----+--------+--------+------+
| id | value1 | value2 | n    |
+----+--------+--------+------+
|  1 |      1 | A      |    1 |
|  2 |      1 | B      |    1 |
|  3 |      2 | A      |    1 |
|  4 |      3 | A      |    1 |
|  5 |      3 | A      |    2 |
|  6 |      3 | B      |    1 |
|  7 |      3 | A      |    3 |
+----+--------+--------+------+