这是mytable中的数据:
select Name, LastName, Id, LocationId, Date, Time, RN from mytable
Name LastName Id LocationId Date Time RN
Office Jones 284 NY 20171004 1540 1
Office Jones 284 NY 20171004 1545 2
Office Jones 284 NY 20171004 1550 3
Office Jones 284 NY 20171004 1650 4
Office Jones 284 NY 20171113 1030 1
Office Jones 284 NY 20171113 1035 2
Office Jones 284 NY 20171113 1040 3
Office Jones 284 NY 20171113 1130 4
Office Jones 284 NY 20171113 1135 5
Office Jones 284 NY 20171113 1140 6
Office Jones 284 NY 20171113 1230 7
Office Jones 284 NY 20171113 1435 8
Office Jones 284 NY 20171113 1740 9
Office Jones 284 NY 20171113 1840 10
Office Jones 284 NY 20171115 1030 1
Office Jones 284 NY 20171115 1035 2
Office Jones 284 NY 20171115 1040 3
我想根据按日期分组的3个连续行显示我的结果名称,姓氏,姓名,位置ID,日期,分钟(时间)
Name LastName Id LocationId Date Time
Office Jones 284 NY 20171004 1540
Office Jones 284 NY 20171113 1030
Office Jones 284 NY 20171113 1130
Office Jones 284 NY 20171113 1230
Office Jones 284 NY 20171115 1030
这是我到目前为止所做的,但我无法弄清楚如何将其他2行纳入我的结果
SELECT Name, LastName, Id, LocationId, Date, min(Time) as Time FROM mytable
WHERE Date IN (SELECT Date
FROM mytable
WHERE RN = 3)
GROUP BY Name, LastName, Id, LocationId, Date
Name LastName Id LocationId Date Time
Office Jones 284 NY 20171004 1540
Office Jones 284 NY 20171113 1030
Office Jones 284 NY 20171115 1030
答案 0 :(得分:2)
如何在rn
上使用算术?
select name, lastname, id, locationid, date, min(time)
from t
group by name, lastname, id, locationid,
(rn - 1) / 3;
或者只有一个where
:
select name, lastname, id, locationid, date, time
from t
where rn % 3 = 1;
答案 1 :(得分:0)
这是一个简化版本,删除常量值列,只关注计算所需的列(我将其转储到临时表中)。内连接中的派生表确定最大行数,每个日期是三的倍数,并且三个结果的聚类在外部查询的分组上:
select #tmp.dates,
min(#tmp.times)
from #tmp
inner join (select dates,
max(rnum) rnum_x
from #tmp
where rnum % 3 = 0
group by dates ) x
on #tmp.dates = x.dates
and #tmp.rnum <= x.rnum_x
group by #tmp.dates,
case when rnum%3 = 0
then rnum/3 - 1
else rnum/3
end