Click here to Skip to main content
15,881,881 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
SQL
DECLARE @t varchar(4000)
Declare @f varchar(4000)
declare @strs as varchar(4000)

CREATE TABLE #tempTab1(
--DateofObservation1 datetime,
SMW nvarchar(2),
VillageName nvarchar(200),
Result1 decimal(8,2)
 )

insert into #tempTab1(VillageName,SMW,Result1)

		select   [Village Name] ,SMW,AVG(Result) Result from
	(
	 Select DateofObservation1, SMW,VillageName as 'Village Name',Result from VillageDetails inner join (
		SELECT  DateofObservation DateofObservation1, dbo.GetStdWeek(DateofObservation) SMW, 
							  v.VillageID,cast(AVG(dbo.PestIncidenceData.ObservationValue)as numeric(10,2)) AS  'Result'
		FROM    dbo.PestIncidenceData INNER JOIN
				dbo.PestIncidenceMaster ON dbo.PestIncidenceData.PestIncidenceMasterID = dbo.PestIncidenceMaster.PestIncidenceMasterID INNER JOIN
				dbo.FieldDetails ON dbo.PestIncidenceMaster.FieldID = dbo.FieldDetails.FieldID
				inner join VillageDetails v on Fielddetails.VillageID=v.VillageID
				inner join DistrictDetails d on d.DistrictID=v.DistrictID
		WHERE  (d.DistrictID =34 ) and (dbo.FieldDetails.Season =1) AND (dbo.FieldDetails.FieldNumber LIKE 'Random%') 
		       AND (dbo.PestIncidenceData.PestID =1)  and ObservationValue<>99999
		       and (dbo.GetStdWeek(dateofObservation )between 45 and 45)
		GROUP BY dbo.PestIncidenceMaster.DateofObservation,v.VillageID) A on VillageDetails.VillageId=A.VillageId
			) as a  group by SMW,[Village Name]  order by SMW
		
		SET @t = ''
		SELECT @t = @t + ', '  + SMW From #tempTab1 group by SMW
		SELECT @f=STUFF(@t,1,2,'')	
		set @strs='SELECT VillageName,'+ @f + ' from  
		(select  VillageName,Result1 from #tempTab1) ps 
		PIVOT
		(
		Avg(Result1) 
		for SMW IN 
		('+ @f+')) As pvt'
		exec (@strs)
		drop table #tempTab1


note: i got error when execute this code in sql
(7 row(s) affected)
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near '45'.


basically i want to pivot the output of store procedure query.
so please help me if any one know.
Posted
Updated 10-Aug-15 20:17pm
v2
Comments
Maciej Los 11-Aug-15 2:25am    
Terrible format of sql query syntax. Improve formatting and provide entire error message (including error number).
DamithSL 11-Aug-15 2:30am    
what is the point of having between 45 and 45?

1 solution

Please, read my command to the question.

In my opinion, there's too many nested SELECT statements. It might be the reason of trouble. I do strongly recommend to re-write this query to make it more readible and finally to improve performance.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900