2011-02-06 74 views
0

我有一張表,其中包含房屋屬性的列表信息。一個物業可能會在表格中多次出現,每次出現一次。以下是相關列:使用聚合函數和group by by where子句的SQL更新查詢?

ListingID <- primary key 
PropertyID 
ListingEndDateTime 

我試圖建立一個查詢來更新爲最近清單表中的每個屬性的EndDateTime。查詢將爲每個屬性設置EndDateTime爲相同的值。

我已經嘗試了幾種方法,迄今爲止不成功。我如何編寫這樣的查詢?

+0

謝謝大家誰公佈。我沒有意識到我應該一直在做複雜的東西作爲更新條款的一部分,而不是試圖在where子句中做到這一點。 – poke 2011-02-06 04:04:37

+0

隨時upvote任何答案,你發現有幫助;) – 2011-02-06 05:48:40

回答

2

以下假設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(); 
0

這允許多個列表中的每個日期相同的屬性,在這種情況下將使用最新的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隨意,將其設置爲你需要的所有記錄的任何日期。

0

可能需要調整,但你的總體思路(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