I have a database in SQL Server listing maritime incidents containing the date of each.
For a chart illustration I now want to write a SQL statement (for Visual Studio) which gives the total number of incidents for each year.
Example:
2009 2010 (Year – X Axes)
4575 5432 (Years – Y Axes)
The SELECT statement for the X axes, I can write like
SELECT year1, year2 FROM (SELECT 2009 AS year1) AS a, ( SELECT 2010 AS year2) AS b
But what about the second one?
When I write something like:
SELECT totalyear1, totalyear2 FROM (SELECT COUNT(Reference) FROM STO.dbo.STOMaritimeIncidents WHERE [Incident date] = 2010 AS totalyear1) AS a, (SELECT COUNT(Reference) FROM STO.dbo.STOMaritimeIncidents WHERE [Incident date] = 2009 AS totalyear2) AS b
I get Errors like “Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword ‘AS’.”
I would really appreciate if someone can give me an explanation or help me with it. Thanks a lot!
The
AS totalyear1andAS totalyear2alias declarations need to be made on the columns themselves:You can improve this by simply doing this in one query:
And if you don’t mind (or prefer) pivoting the data, you can use @Umair’s suggestion and use COUNT with a GROUP BY clause.