我有一张事件表。主持人可以在一天内创建多个事件。有些事件是经常性的,有些则不是。我有一个复杂的(对我而言)SELECT语句,我认为条件有些如何以及可能是子查询,我真的不知道如何处理它。
选择优先级:
以下是事件表示例:
+----+--------+---------+------------+-----------+
| id | hostid | title | start_date | recurring |
+----+--------+---------+------------+-----------+
| 1 | 1 | Event1A | 2016-10-01 | 1 |
| 2 | 1 | Event1B | 2016-10-01 | 0 |
| 3 | 1 | Event1C | 2016-10-02 | 0 |
| 4 | 1 | Event1D | 2016-10-02 | 1 |
| 5 | 1 | Event1E | 2016-10-02 | 1 |
| 6 | 1 | Event1F | 2016-10-03 | 1 |
| 7 | 1 | Event1G | 2016-10-03 | 1 |
| 8 | 1 | Event1H | 2016-10-04 | 1 |
| 9 | 1 | Event1I | 2016-10-05 | 0 |
| 10 | 2 | Event2A | 2016-10-01 | 1 |
| 11 | 2 | Event2B | 2016-10-01 | 0 |
| 12 | 2 | Event2C | 2016-10-02 | 1 |
| 13 | 2 | Event2D | 2016-10-03 | 0 |
+----+--------+---------+------------+-----------+
以下是我想要的结果:
+----+--------+---------+------------+-----------+
| id | hostid | title | start_date | recurring |
+----+--------+---------+------------+-----------+
| 2 | 1 | Event1B | 2016-10-01 | 0 |
| 3 | 1 | Event1C | 2016-10-02 | 0 |
| 6 | 1 | Event1F | 2016-10-03 | 1 |
| 7 | 1 | Event1G | 2016-10-03 | 1 |
| 8 | 1 | Event1H | 2016-10-04 | 1 |
| 9 | 1 | Event1I | 2016-10-05 | 0 |
| 11 | 2 | Event2B | 2016-10-01 | 0 |
| 12 | 2 | Event2C | 2016-10-02 | 1 |
| 13 | 2 | Event2D | 2016-10-03 | 0 |
+----+--------+---------+------------+-----------+
这是一个带有表格的SQL Fiddle链接:
答案 0 :(得分:1)
任务相当简单:您希望每个主机和日期的记录具有最小的重复标记。
select events.*
from
(
select hostid, start_date, min(recurring) as recurring
from events
group by hostid, start_date
) chosen
join events on events.hostid = chosen.hostid
and events.start_date = chosen.start_date
and events.recurring = chosen.recurring
order by events.id;
这是你的SQL小提琴:http://sqlfiddle.com/#!9/6427e/59: - )
答案 1 :(得分:0)
一位朋友帮我找到了这个解决方案:
SELECT e.*
FROM Events e
LEFT JOIN (
SELECT start_date,
hostid,
count(*) cnt,
AVG(Cast(recurring as decimal)) recur
FROM Events
GROUP BY start_date, hostid
) r
ON e.start_date = r.start_date
AND e.hostid = r.hostid
WHERE (e.recurring = 0 and r.recur <> 1)
OR r.recur = 1 OR r.cnt = 1
ORDER BY e.id