Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Problem with totalize per quarter
Message
From
20/08/2016 16:27:22
 
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Environment versions
SQL Server:
SQL Server 2012
OS:
Windows 10
Network:
Windows Server 2012
Miscellaneous
Thread ID:
01639700
Message ID:
01639713
Views:
80
>>I need to create a query with columns containing quarterly figures. I figured I could handle that with subqueries, but I am trying to make this work for a long time already and it still does not seem right.
>>The final result now gives the correct figures, but I cannot add the last quarter to it because of the join with the GL accounts, if there is no result in the subquery, it drops the entire line.
>>I must be doing something wrong, but I can't figure out how to correct it.
>
>I agree with Sergey - this is the kind of query where PIVOT will very likely help you.
>
>If you've never used PIVOT before, I'll be glad to help - if you'll post the DDL/Table structure for the tables involved. Don't need any data - just the table structures.

This is now my final version with Pivot. At first I was reluctant to dive into Pivot but in hindsight it's easier than I expected. The result is exactly what I need:
SELECT Ministerie, Departement, KSC, Kostensoort,
		Year,
		ISNULL(QPivot.[1],0.00) + 
		ISNULL(QPivot.[2],0.00) + 
		ISNULL(QPivot.[3],0.00) + 
		ISNULL(QPivot.[4],0.00) AS Total, 

		ISNULL(QPivot.[1],0.00) AS Q1,
		ISNULL(QPivot.[2],0.00) AS Q2,
		ISNULL(QPivot.[3],0.00) AS Q3,
		ISNULL(QPivot.[4],0.00) AS Q4
		
FROM (SELECT DepGroups.dgName AS Ministerie,
		Departments.deName AS Departement,
		GLSub.gsAccount AS KSC,
		GLSub.gsDescr AS Kostensoort,
		DATEPART(YEAR,Runs.ruStartDat) AS Year,
		DATEPART(Quarter, Runs.ruStartDat) AS Quarter,
		SUM(itAmount) AS itAmount

	FROM PayEmps
	
	JOIN Departments
	ON Departments.DeKey = PayEmps.paDeKey
	JOIN DepGroups
	ON Departments.deDgKey = DepGroups.dgKey
	JOIN Runs
	ON Runs.ruKey = PayEmps.paRuKey

	LEFT JOIN HistItems Items
	ON Items.itRuKey = Runs.ruKey
	AND Items.itEmKey = PayEmps.paEmKey

	LEFT JOIN GLSub
	ON Items.itGsKey = GLSub.gsKey

	WHERE PayEmps.delFlag = 0
			AND Runs.DelFlag = 0
			AND Runs.ruConcept = 0
			AND Runs.ruStatus = 5
			AND DATEPART(YEAR,Runs.ruStartDat) = ?pnYear
			AND Items.DelFlag = 0
		        AND GsAccount = '4101'
                        AND Runs.ruYear = 2015

	GROUP BY DepGroups.dgName, Departments.deName, 
		GLSub.gsAccount, GLSub.gsDescr,
		DATEPART(YEAR,Runs.ruStartDat),
		DATEPART(QUARTER,Runs.ruStartDat)) AS QuarterlyData
	
	PIVOT(SUM([itAmount])   
        FOR QUARTER IN ([1],[2],[3],[4])) AS QPivot

	ORDER BY Ministerie, Departement, KSC
Christian Isberner
Software Consultant
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform