我有一张表,其中包含房屋属性的列表信息。一个物业可能会在表格中多次出现,每次出现一次。以下是相关列:使用聚合函数和group by by where子句的SQL更新查询?
ListingID <- primary key
PropertyID
ListingEndDateTime
我试图建立一个查询来更新为最近清单表中的每个属性的EndDateTime。查询将为每个属性设置EndDateTime为相同的值。
我已经尝试了几种方法,迄今为止不成功。我如何编写这样的查询?
我有一张表,其中包含房屋属性的列表信息。一个物业可能会在表格中多次出现,每次出现一次。以下是相关列:使用聚合函数和group by by where子句的SQL更新查询?
ListingID <- primary key
PropertyID
ListingEndDateTime
我试图建立一个查询来更新为最近清单表中的每个属性的EndDateTime。查询将为每个属性设置EndDateTime为相同的值。
我已经尝试了几种方法,迄今为止不成功。我如何编写这样的查询?
以下假设ListingID是auto_incrementing主键:
update PropertyListing p
inner join
(
select
max(ListingID) as ListingID,
PropertyID
from
PropertyListing
group by
PropertyID
) latest on latest.ListingID = p.ListingID
set
p.ListingEndDateTime = now();
这允许多个列表中的每个日期相同的属性,在这种情况下将使用最新的ListingID。否则,只有最新的日期才能确定列表。
# create table PropertyListing(ListingEndDateTime Int, PropertyID Int, ListingID Int);
update PropertyListing L
inner join
(
select Max(B.ListingID) MaxListingID
FROM
(
select PropertyID, MAX(ListingEndDateTime) MaxListingEndDateTime
from PropertyListing
group by PropertyID
) A
inner join PropertyListing B
on B.ListingEndDateTime = A.MaxListingEndDateTime and A.PropertyID = B.PropertyID
group by B.PropertyID, B.ListingEndDateTime
) C on C.MaxListingID = L.ListingID
set L.ListingEndDateTime = CURDATE() + 7;
我用CURDATE() + 7
随意,将其设置为你需要的所有记录的任何日期。
可能需要调整,但你的总体思路(SQL服务器2005年起):
WITH cteMostRecent (PropertyID, ListingEndDateTime, rownum) AS
(
SELECT PropertyID, ListingEndDateTime,
ROW_NUMBER() OVER (PARTITION BY PropertyID ORDER BY ListingEndDateTime DESC) as rownum
FROM MyListingTable
)
UPDATE cteMostRecent
SET ListingEndDateTime = someDate
WHERE rownum = 1
谢谢大家谁公布。我没有意识到我应该一直在做复杂的东西作为更新条款的一部分,而不是试图在where子句中做到这一点。 – poke 2011-02-06 04:04:37
随时upvote任何答案,你发现有帮助;) – 2011-02-06 05:48:40