计算发生次数并显示MYSQL中的最后一次发生

时间:2019-03-01 03:36:52

标签: mysql

我有这张桌子

serie      number
-----      ------
A          1
A          2
A          3
A          5
B          1
B          3

我想显示这样的结果

serie      ocurrences   last_number_value
-----      ----------   -----------------
A          4                          5
B          2                          3

我设法获得了发生次数

SELECT serie, number, COUNT(*) AS ocurrences FROM table_name GROUP BY serie

但是,如何也显示最后一个数字?

1 个答案:

答案 0 :(得分:1)

这将为您找到所需的结果:

CREATE TABLE test (
  serie varchar(1) NOT NULL,
  num int(1) NOT NULL
);

INSERT INTO test (serie, num) VALUES 
('A', 1),
('A', 2),
('A', 3),
('A', 5),
('B', 1),
('B', 3);

如果行顺序很重要:

SELECT 
 a.serie,
 (SELECT count(*) FROM test WHERE serie=a.serie) as occurances,
 a.num
FROM
  test AS a
  LEFT JOIN test AS b on a.serie=b.serie AND a.num<b.num
  WHERE 
b.serie IS NULL;

如果顺序或行无关紧要:

SELECT 
  a.serie,
  COUNT(*) AS occurances,
  MAX(a.num) AS last_number_value
FROM
  test AS a
GROUP BY a.serie;