这是我的问题;
我运行此查询并获得13469个具有多行的用户,其中'FirstTimeBooking'= 1:
Select CustUserId, COUNT(CustUserId)
FROM Bookings with (nolock)
WHERE FirstTimeBooking = 1
GROUP BY CustUserId
HAVING COUNT(CustUserId) > 1
ORDER BY COUNT(CustUserId) DESC
我需要更新所有这些记录,为每个行设置FirstTimeBooking = 0除了每个用户的Min(BookingDate)(这是实际的FirstTimeBooking)。任何帮助将不胜感激。
答案 0 :(得分:1)
我试图保持简单并保持语法:
CREATE TABLE Bookings
(
CustUserID int
,FirstTimeBooking int
,BookingDate datetime
)
INSERT INTO Bookings VALUES
(1, 1, '20170101')
,(1, 1, '20170101') -- Duplicate on same date
,(2, 1, '20170201')
,(2, 1, '20170301') -- On a second date
,(3, 1, '20170401')
UPDATE a
SET FirstTimeBooking = 0
FROM Bookings as a
LEFT OUTER JOIN (
-- Only CustUserID 1 and 2
SELECT CustUserID, min(BookingDate) as BookingDate
FROM Bookings
WHERE FirstTimeBooking = 1
GROUP BY CustUserID
HAVING COUNT(*) > 1
) as b
on a.CustUserID = b.CustUserID
and a.BookingDate = b.BookingDate
WHERE b.BookingDate IS NULL -- only where the first booking date has not been found in subquery
-- Still got the Problem with CustUserID
SELECT *
FROM Bookings
WHERE CustUserID = 1
UPDATE b
set FirstTimeBooking = 0
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CustUserID ORDER BY CustUserID) As Rown
FROM Bookings as b
WHERE FirstTimeBooking = 1
) as b
WHERE Rown = 2
-- This is now also solved
SELECT *
FROM Bookings
WHERE CustUserID = 1
也许你没有两个相同的预订日期,但我加上这个以防万一。
此致 TGR