我花了一些時間在此,我相信我解決了您的所有擔憂。我不完全確定城市或位置的數據類型,所以我用varchar(100)這應該解決你所有的擔憂。請評論是否存在您描述過這種情況並未解決的情況。
CREATE PROCEDURE [dbo].[GetRecentlyListedProperties]
(@location varchar(100), @city varchar(100),@propertyID int)
As
Begin
DECLARE @numberOfDays int,
@propertyCount int,
@IsLocation bit -- looking for a location and not a city
SET @Propertycount = 0
SET @numberOfDays= 10
-- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 10 DAYS IN THE SAME LOCATION
SELECT @PropertyCount =
Count(*) FROM properties where location = @location and DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
and PropertyID != @propertyID
If(@PropertyCount = 0)
Begin
-- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 10 DAYS IN THE SAME CITY
SELECT @PropertyCount = Count(*) from properties where city = @city
AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
AND PropertyID != @propertyID
IF(@PropertyCount = 0)
BEGIN
SET @NumberOfDays = 30
-- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 30 DAYS IN THE SAME LOCATION
SELECT @PropertyCount = COUNT(*) from properties where location = @location
AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
AND PropertyID != @propertyID
IF(@PropertyCount = 0)
BEGIN
-- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 30 DAYS IN THE SAME CITY
SELECT @PropertyCount = Count(*) from properties where city = @city
AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
AND PropertyID != @propertyID
END
ELSE
SET @IsLocation = 1 --There are properties in the same location in the last 30 days
END
ELSE
SET @IsLocation = 0 -- There are properties listed int he city in the last 10 days
End
Else
SET @IsLocation = 1
-- This is where the appropriate results are returned.
IF(@IsLocation = 1)
Begin
SELECT * ,(SELECT AVG(PRICE) as AveragePrice
FROM PROPERTIES
WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
AND Location = @Location
AND PropertyID != @propertyID)
FROM Properties
WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
AND Location = @Location
AND PropertyID != @propertyID
End
ElSE
SELECT * ,(SELECT AVG(PRICE) as AveragePrice
FROM PROPERTIES
WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
AND City = @City
AND PropertyID != @propertyID)
FROM Properties
WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
AND City = @City
AND PropertyID != @propertyID
End
您可能必須更改位置和城市的外鍵的某些數據類型,因爲我將它們用作varchars。
社區wiki?真的嗎?我猜爲什麼失敗的興趣回答了這個問題,那肯定不是社區wiki的候選人。 – 2010-02-14 18:08:55
您是否需要在一個查詢中執行此操作? – RobS 2010-02-20 13:19:51
是... Plz幫助! – Sanju 2010-02-22 06:38:57