Mysql计数出现次数

时间:2013-05-16 21:53:10

标签: mysql database

所以我们假设我们有以下数据表:

A   |   B
_________
1   |   2
3   |   4
5   |   6
6   |   5

如果我想计算相同数字碰撞或在同一行中的次数怎么办?所以在上面的示例中,1-2和3-4将返回一个计数,因为它们只在同一行上一次,但5-6和6-5将返回值为2.

更真实的插图:认为数字是体育团队ID,A和B栏确定主持人团队和客队。 Ao队5和6队总共打了2场比赛,第一队5队作为主队,第6队作为东道主。

那我怎么能在mysql中算这些呢?

3 个答案:

答案 0 :(得分:1)

DROP TABLE IF EXISTS fixtures;
CREATE TABLE fixtures
(fixture_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,home INT NOT NULL
,away INT NOT NULL
);

INSERT INTO fixtures (home,away) VALUES (1,2),(3,4),(5,6),(6,5);

SELECT * FROM fixtures;
+------------+------+------+
| fixture_id | home | away |
+------------+------+------+
|          1 |    1 |    2 |
|          2 |    3 |    4 |
|          3 |    5 |    6 |
|          4 |    6 |    5 |
+------------+------+------+

SELECT LEAST(home,away) a,GREATEST(home,away) b, COUNT(*) ttl FROM fixtures GROUP BY a,b;
+---+---+-----+
| a | b | ttl |
+---+---+-----+
| 1 | 2 |   1 |
| 3 | 4 |   1 |
| 5 | 6 |   2 |
+---+---+-----+

答案 1 :(得分:0)

由于a-b与b-a相同,您希望将该结果标准化:

SELECT LEAST(a,b) AS x, GREATEST(a,b) AS y ...

现在您可以计算出现次数:

SELECT LEAST(a,b) AS x, GREATEST(a,b) AS y, count(*) as c FROM tablename GROUP BY x,y

迎接

答案 2 :(得分:0)

SELECT
CASE WHEN A < B THEN A ELSE B END AS aa,
CASE WHEN B > A THEN B ELSE A END AS bb,
COUNT(*)
FROM
Table1 t1
GROUP BY aa, bb

sqlfiddle中查看。