0

So lets say we have the following table of data:

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

And what if I wanted to count the times the same numbers collide or are in the same line? So in the above example 1-2 and 3-4 would return a count of one because they are on the same line only once however 5-6 and 6-5 would return a value of 2.

A more real life illustration: think that the numbers are sport team id's and the A and B columns determine the host-team and the guest-team. Ao teams 5 and 6 have played a total of 2 games against each other, first team 5 as a host and then team 6 as a host.

So how could I count these in mysql?

4

3 回答 3

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 |
+---+---+-----+
于 2013-05-17T00:20:12.803 回答
0

由于 ab 与 ba 相同,因此您希望对该结果进行归一化:

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

问候

于 2013-05-16T22:23:32.360 回答
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中看到它。

于 2013-05-16T23:26:06.187 回答