我有一个表“玩家”如下 哪里: ID是主键。
这是表格
+----+------------+-------+-------------+
| ID | Date | Name | Sport |
+----+------------+-------+-------------+
| 1 | 1 | A | football |
| 2 | 1 | A | soccer |
| 3 | 3 | A | tennis |
| 4 | 2 | B | tennis |
| 5 | 2 | B | football |
| 6 | 1 | C | basketball |
| 7 | 1 | C | tennis |
| 8 | 1 | C | fishing |
+----+------------+-------+-------------+
我想找到所有在一天内参加超过2项运动的人(名字和运动),其中一项运动必须是“足球”。
所以结果应该是这样的,
+----+------+------+----------+
| ID | Date | Name | Sport |
+----+------+------+----------+
| 1 | 1 | A | football |
| 2 | 1 | A | soccer |
| 4 | 2 | B | tenis |
| 5 | 2 | B | football |
+----+------+------+----------+
我们不计算名字“C”,因为他不踢足球(即使他在一天内参加超过2项运动)。
我试试
SELECT * FROM player GROUP BY Date, Name HAVING count(Date) > 1;
但不会给我我想要的东西。
PS:这篇文章不是重复的帖子。 Finding duplicate values in MySQL中的答案 不会直接针对这个问题。这是找到具有重复值和条件的行。请删除“重复”标记,以便其他人可以从此问题中受益。
答案 0 :(得分:3)
你应该寻找这个:
表格pl1
已匹配player name
和date
已玩football
,pl2
包含计数,pl3
可让您获得所有这些玩家谁在特定日期玩了football
个以及更多游戏,然后从pl4
SELECT
pl4.*
FROM
player pl4
JOIN
(SELECT
pl2.name, pl2.date, COUNT(pl2.name) numberofgames
FROM
player pl2
JOIN (SELECT
date, name
FROM
player
WHERE
sport = 'football') pl1 ON (pl2.name = pl1.name
AND pl2.date = pl1.date)
GROUP BY pl2.name , pl2.date
HAVING numberofgames > 1) pl3 ON (pl3.name = pl4.name
AND pl3.date = pl4.date)
答案 1 :(得分:2)
尝试:
select
a.*
from tbl a
join (
select
date, name,
max(case when Sport = 'football' then 1 else 0 end) val
from tbl
group by date, name
having count(date) > 1
) b on a.date = b.date and a.name = b.name
where b.val = 1
演示 sqlfiddle