排除相同的值和特定的规则集查询

时间:2019-02-04 14:50:36

标签: mysql sql

自从我使用数据库以来已经有一段时间了,目前还不能全神贯注地去做这些事情,所以如果有人可以帮我解决这两个问题/疑问,我将非常感谢。

  1. 我想显示至少在2个不同区域内的ID(不包括仅在同一区域内的ID)。

  2. 我想显示首先在zone1中,然后在zone2中,然后在zone3中的ID(需要在此处查看时间)。

原文:

ID    ZONE    TIME 
"01"  "ZO1"   "20190110_111326"
"01"  "ZO1"   "20190110_111355" 
"01"  "ZO1"   "20190110_111529"
"02"  "ZO3"   "20190110_112527"
"02"  "ZO3"   "20190110_112559"
"06"  "ZO1"   "20190114_082144" 
"06"  "ZO2"   "20190114_082153"
"06"  "ZO3"   "20190114_082210" 
"07"  "ZO3"   "20190114_131034"
"07"  "ZO2"   "20190114_131058"

1。

ID      ZONE    TIME
"06"    "ZO1"   "20190114_082144"
"06"    "ZO2"   "20190114_082153"
"06"    "ZO3"   "20190114_082210"
"07"    "ZO3"   "20190114_131034"
"07"    "ZO2"   "20190114_131058"

2。

ID      ZONE    TIME
"06"    "ZO1"   "20190114_082144"
"06"    "ZO2"   "20190114_082153"
"06"    "ZO3"   "20190114_082210"

1 个答案:

答案 0 :(得分:0)

回答#1

select * from table where id in 
(
select id from
(
   select id, zone
   from table 
   group by id, zone
)
group by id 
having count(1) > 1

)

回答#2

select t2.zone, t2.time, max(t2.id) as id from 
(select zone, min(time) minTime from table group by zone ) t1
join 
(select id, zone, time from table) t2 on t1.zone = t2.zone and t1.minTime = t2.time
group by t2.zone, t2.time

请注意,第二个查询获得最大ID的原因是b / c可能同时存在多个ID。