MySQL中的对计数
我需要找出一个值存在多少对 我的桌子上有3匹像这样的马MySQL中的对计数,mysql,Mysql,我需要找出一个值存在多少对 我的桌子上有3匹像这样的马 +----+----------+------+-----------------+ | id | one | two | three | +----+----------+------+-----------------+ | 1 | steve | bob | michael | | 2 | bob | steve| chris | | 3 |
+----+----------+------+-----------------+
| id | one | two | three |
+----+----------+------+-----------------+
| 1 | steve | bob | michael |
| 2 | bob | steve| chris |
| 3 | chris | sam | NULL |
| 4 | michael | chris| lea |
| 5 | steve | lea | NULL |
| 6 | susan | chris| steve |
| 7 | lea | steve| bob |
现在,我想为史蒂夫找到一对,包括他们的计数。。。第3列为“可选”(可以包含null),并且始终填充“一”和“二”
结果应该是:史蒂夫和莉亚2,史蒂夫和鲍勃2,史蒂夫和克里斯3,史蒂夫和迈克尔1,史蒂夫和苏珊1
编辑:更好的示例(数据方面)是:
+----+--------+--------+--------+--------+
| id | url | color1 | color2 | color3 |
+----+--------+--------+--------+--------+
| 1 | foo.com| red | grey | |
| 2 | a.com | white | red | grey |
| 3 | b.com | black | white | |
| 4 | z.com | white | red | |
| 5 | 123.com| white | grey | black |
颜色1、2、3是站点使用的最突出的颜色(至少2、可选3)。
结果应该是一个最常见的颜色组合列表。希望这些示例更有意义。如果我正确理解了您的问题,我不确定,但鉴于以下示例数据:
SELECT
CONCAT(one, " & ", two), count(*)
FROM
myTable
GROUP BY
1
CREATE TABLE t
(`id` int, `one` varchar(7), `two` varchar(5), `three` varchar(7))
;
INSERT INTO t
(`id`, `one`, `two`, `three`)
VALUES
(1, 'steve', 'bob', 'michael'),
(2, 'bob', 'steve', 'chris'),
(3, 'chris', 'sam', NULL),
(4, 'michael', 'chris', 'lea'),
(5, 'steve', 'lea', NULL),
(6, 'susan', 'chris', 'steve'),
(7, 'lea', 'steve', 'bob')
;
我接受这个问题
select
least(a, b) as p1, greatest(a, b) as p2, count(*)
from (
select
one as a, two as b
from
t
where 'steve' in (one, two)
union all
select
one, three
from
t
where 'steve' in (one, three)
union all
select
two, three
from
t
where 'steve' in (two, three)
) sq
group by p1, p2
这一结果:
| P1 | P2 | COUNT(*) |
|---------|--------|----------|
| (null) | (null) | 1 |
| bob | steve | 3 |
| chris | steve | 2 |
| lea | steve | 2 |
| michael | steve | 1 |
| steve | susan | 1 |
这就是你要找的吗
- 在这里面玩吧