Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Sum a col for MTD and another for YTD in same query?
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01197144
Message ID:
01197152
Views:
18
This message has been marked as the solution to the initial question of the thread.
Try
DECLARE @YEAR int
DECLARE @PrevMonth int

SET @Year = YEAR(getdate())
SET @PrevMonth = MONTH(DATEADD(mm, -1, getdate()))

select site, impactedMedia, incidentCategory, 
		SUM( CASE WHEN Year(EventDate) = @Year 
					AND month(EventDate) = @PrevMonth
				THEN 1 ELSE 0 END) AS MTD, 
		SUM( CASE WHEN Year(EventDate) = @Year 
					AND month(EventDate) <= @PrevMonth
				THEN 1 ELSE 0 END) AS YTD
	from tb_EnvIncident
	left join 
		tb_sc_data_codes
			on impactedMedia = code 
				and codetype = 'iris_EnvImpactedMedia'
				AND Status = 'Approved'
	group by site, impactedMedia, incidentCategory
>I am doing an accident report where I have to sum last month's accidents as well as my YTD for display. I have set a union for each total into a Temp table and I then sum what is there for output.
>
>Below is the code. Can you think of a better way in a single query to get both columns or is this the best method I have available?
>
<snip>
--sb--
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform