使用groupby子句更新相同的表n记录

hfwmuf9z  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(257)

我使用的是mysql数据库,我有一个时隙表,根据允许的计数(n)记录,特定日期的不同时隙应该更新为有效。

CREATE  TABLE tmpSlots(
    SlotID INT AUTO_INCREMENT PRIMARY KEY  ,
    StartSlot DATETIME,
    EndSlot DATETIME,
    Valid BOOLEAN DEFAULT 0
);  
insert into tmpSlots VALUES(1,'2020-08-01 08:30:00', '2020-08-01 09:10:00',0 );
insert into tmpSlots VALUES(2,'2020-08-01 09:30:00', '2020-08-01 10:10:00',0 );
insert into tmpSlots values(3,'2020-08-01 10:30:00', '2020-08-01 11:10:00',0 );
insert into tmpSlots values(4,'2020-08-01 12:30:00', '2020-08-01 13:10:00',0 );
insert into tmpSlots values(5,'2020-08-07 08:30:00', '2020-08-07 09:10:00',0 );
insert into tmpSlots values(6,'2020-08-07 09:30:00', '2020-08-07 10:10:00',0 );
insert into tmpSlots values(7,'2020-08-07 10:30:00', '2020-08-07 11:10:00',0 );
insert into tmpSlots values(8,'2020-08-07 12:30:00', '2020-08-07 13:10:00',0 );

DECLARE permitcount INT ; 
SET permitcount =2;

因为permitcount,所以每天只允许2个插槽前2个记录应更新为valid=true预期结果

UPDATE tmpSlots t1 SET valid=1
FROM  (
  ...........
.
   GROUP  BY Date(StartSlot)
   ) AS sq
WHERE

有人能帮我吗

pxyaymoc

pxyaymoc1#

你可以使用 join 在一个 update . 但是,您不需要聚合。相反,你可以使用 row_number() 枚举每天的值。然后,使用 where 条款:

update tmpslots s join
       (select s2.*,
               row_number() over (partition by date(startslot) order by startslot) as seqnum
        from tmpslots s2
       ) s2
       on s2.slotid = s.slotid
    set s.value = 1
    where s2.seqnum <= 2;

这将基于 startslot .
在早期版本中,我只使用两个更新:

update tmpslots s join
       (select date(startslot) as dte, min(slotid) as min_slotid
        from tmpslots s2
        group by dte
       ) s2
       on s2.min_slotid = s.slotid
    set s.value = 1;

update tmpslots s join
       (select date(startslot) as dte, min(slotid) as min_slotid
        from tmpslots s2
        where s.value = 0
        group by dte
       ) s2
       on s2.min_slotid = s.slotid
    set s.value = 1;

虽然你可以把它编成一个更新,但两个更新似乎更简单。

相关问题