我有这张桌子
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
但是,如何显示最后一个号码呢?
最佳答案
这将为您提供您所需的结果:
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;
关于mysql - 计算出现次数并显示MYSQL中的最后一次出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54937578/