SQL Server:一段时间内启动和停止的直方图

时间:2016-05-10 19:32:05

标签: sql sql-server

我正在尝试从订户数据库中获取启动和停止的直方图,我知道结果应该是什么,但我无法使其工作。

我正在尝试的代码是:

enter image description here

不幸的是我收到了消息

  

Msg 241,Level 16,State 1,Line 2
  从字符串转换日期和/或时间时转换失败。

如果我尝试

enter image description here

它也不起作用:

  

Msg 242,Level 16,State 3,Line 2
  将varchar数据类型转换为日期时间数据类型会导致超出范围的值。

我如何克服这个并获得直方图表?

提前致谢

1 个答案:

答案 0 :(得分:0)

根据您的评论,start_date和stop_date列具有空值。请过滤这些值,而不是CONVERT,请使用CAST,因为您使用的转换会导致某些值出错

样品:

DECLARE @End_date AS VARCHAR(50) = '2016-05-15'; 
SELECT YEAR (CAST(@End_date as DATETIME));
SELECT YEAR (CONVERT(DATETIME, @End_date, 104 ));

注意:我通过查看您的图片手动输入代码。如果有任何错字,请更正。

所以下面的代码可以满足您的期望:

SELECT theyear, SUM(isstart) as starts, SUM(isstop) as stops
FROM ( 
     SELECT YEAR(CAST([start_date] AS DATETIME)) as theyear, 1 as isstart, 0 as isstop
     FROM Subscribers 
     WHERE [start_date] IS NOT NULL

     UNION ALL

     SELECT YEAR(CAST(stop_date AS DATETIME)) as theyear, 0 as isstart, 1 as isstop
     FROM Subscribers
     WHERE stop_date IS NOT NULL
)s
GROUP BY theyear
ORDER BY theyear