Hi,I'm trying to construct a query which will take the results of a query which provides the number of houses of a particular type, in a particular postcode sold in a particular month, of a particular year - see belowSELECT @NoSoldInMonth = NoOFHouses, @currentMonth = Query1.Month FROM (SELECT Postout, HouseType, Year(Application_Date) AS Year, MONTH(Application_Date) AS Month, AVG(decPrice) AS AveragePrice, MIN(decPrice) AS MinPrice, MAX(decPrice) AS MaxPrice, COUNT(*) AS NoOfHouses FROM dbo.Postcode_Datesplit GROUP BY YEAR(Application_Date),MONTH(Application_Date), Postout, HouseType) AS Query1 WHERE Query1.NoOFHouses <10
I then want to run through a loop for each line of results from the above query, because if a particular group does not contain 10 or more houses sold I want to merge it with the following group and so on until the merged groups *do* contain 10 or more houses sold, in order to provide a more accurate average. Here's the code for the loopWHILE (@NoSoldInMonth < 10)BEGIN; INSERT INTO [MyHousePrice].[dbo].[TempTable] ([ID] ,[decPrice] ,[Application_Date] ,[Postcode] ,[HouseType] ,[NewBuild] ,[LeaseStatus] ,[SAON] ,[PAON] ,[Thoroughfare] ,[Locality] ,[Town] ,[District] ,[County] ,[Easting] ,[Northing] ,[strAddress] ,[PostOut] ) SELECT [ID] ,[decPrice] ,[Application_Date] ,[Postcode] ,[HouseType] ,[NewBuild] ,[LeaseStatus] ,[SAON] ,[PAON] ,[Thoroughfare] ,[Locality] ,[Town] ,[District] ,[County] ,[Easting] ,[Northing] ,[strAddress] ,[PostOut] FROM Postcode_DateSplit WHERE (MONTH(Application_Date) = @currentMonth) AND @currentHouseType = HouseType AND (YEAR(Application_Date) = @currentYear OR (YEAR(Application_DATE) = (@CurrentYear+1) AND MONTH(Application_Date)=1)) AND PreviouslyUsedFlag IS NULLSELECT @NoSoldInMonth = COUNT(*) FROM Postcode_DateSplit WHERE (MONTH(Application_Date) = @currentMonth) AND @currentHouseType = HouseType AND (YEAR(Application_Date) = @currentYear OR (YEAR(Application_DATE) = (@CurrentYear+1) AND MONTH(Application_Date)=1)) AND PreviouslyUsedFlag IS NUllSELECT @currentPostout = [postout] FROM Postcode_DateSplit WHERE (MONTH(Application_Date) = @currentMonth) AND @currentHouseType = HouseType AND (YEAR(Application_Date) = @currentYear OR (YEAR(Application_DATE) = (@CurrentYear+1) AND MONTH(Application_Date)=1)) AND PreviouslyUsedFlag IS NUllset @currentMonth = @currentMonth+1IF @currentMonth=13 BEGIN SET @currentMonth = 1 SET @currentYear = @currentYear+1 ENDUPDATE Postcode_DateSplit SET PreviouslyUsedFlag = 'Yes' WHERE (MONTH(Application_Date) = @currentMonth) AND @currentHouseType = HouseType AND (YEAR(Application_Date) = @currentYear OR (YEAR(Application_DATE) = (@CurrentYear+1) AND MONTH(Application_Date)=1))END;
I'm concerned that the current code is essentially running two seperate unrelated queries and not doing what I'm trying to achieve.I'm only really used to using simple SELECT statements in SQL.Any help is greatly appreciated.Thanks