0

我在 SQL Server 中有一个数据库,列出了包含每个日期的海事事件。对于图表说明,我现在想编写一个 SQL 语句(用于 Visual Studio),它给出了每年的事件总数。

例子:

2009 2010(年 - X 轴)

4575 5432(年 - Y 轴)

X 轴的 SELECT 语句,我可以这样写

SELECT year1, year2 FROM (SELECT 2009 AS year1) AS a, ( SELECT 2010 AS year2) AS b

但是第二个呢?当我写类似的东西时:

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

我收到类似“ Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'AS' 之类的错误。”

如果有人能给我一个解释或帮助我,我将不胜感激。非常感谢!

4

2 回答 2

1

需要在列本身上进行和别名声明AS totalyear1AS totalyear2

SELECT totalyear1, totalyear2 
FROM (SELECT COUNT(Reference) AS totalyear1 
      FROM STO.dbo.STOMaritimeIncidents 
      WHERE [Incident date] = 2010) AS a, 
     (SELECT COUNT(Reference) AS totalyear2 
      FROM STO.dbo.STOMaritimeIncidents 
      WHERE [Incident date] = 2009) AS b

您可以通过简单地在一个查询中执行此操作来改进这一点:

SELECT SUM(CASE WHEN [Incident date] = 2010 THEN 1 ELSE 0) as totalyear1,
       SUM(CASE WHEN [Incident date] = 2009 THEN 1 ELSE 0) as totalyear2
FROM STO.dbo.STOMaritimeIncidents

如果您不介意(或更喜欢)旋转数据,您可以使用@Umair 的建议并将 COUNT 与 GROUP BY 子句一起使用。

于 2013-01-16T17:10:58.793 回答
0

ps 你可以在一个查询中完成所有事情!如

SELECT [Incident date], Total = COUNT(Reference) 
FROM STO.dbo.STOMaritimeIncidents
GROUP BY [Incident date]
WHERE [Incident date] IN (2009, 2010)

至于您的实际错误,是因为行...WHERE [Incident date] = 2009 AS totalyear2等。它需要采用以下格式(别名需要在列上)

SELECT totalyear2 = COUNT(Reference) FROM STO.dbo.STOMaritimeIncidents WHERE [Incident date] = 2010
于 2013-01-16T17:11:09.733 回答