多个独立输出的多个SELECT语句

时间:2013-01-16 17:04:02

标签: sql sql-server visual-studio-2010 stored-procedures sql-function

我在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 关键字“AS”附近的语法不正确。“

如果有人能给我解释或帮助我,我真的很感激。非常感谢!

2 个答案:

答案 0 :(得分: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的建议并使用带有GROUP BY子句的COUNT。

答案 1 :(得分:0)

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

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