Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Sum a col for MTD and another for YTD in same query?
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Divers
Thread ID:
01197144
Message ID:
01197152
Vues:
17
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--
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform