筛选出计算列值为null的行

时间:2013-04-24 15:26:59

标签: sql sql-server

我有一个SQL查询的内容:

SELECT CONVERT(varchar, DATEPART(month, titlStreaming)) + '/' + CONVERT(varchar, DATEPART(day, titlStreaming)) + '/' + CONVERT(varchar, DATEPART(year, titlStreaming)) AS [Day], 
COUNT(titlTitleID) AS Total 
FROM Title
GROUP BY DATEPART(year, titlStreaming), DATEPART(month, titlStreaming), DATEPART(day, titlStreaming)
ORDER BY DATEPART(year, titlStreaming) DESC, DATEPART(month, titlStreaming) DESC, DATEPART(day, titlStreaming) DESC

通常会返回一个表格,如:

Day       |   Total
--------------------
4/23/2013 |       2
         ...
NULL      |   14234

我想要做的是过滤掉返回NULL值的行。 因为Day显然是计算列,所以我不能简单地执行WHERE Day IS NOT NULL。 我承认我对SQL的了解很缺乏,所以任何帮助或建议都会受到赞赏。

2 个答案:

答案 0 :(得分:1)

您可以使用子查询:

select *
from (SELECT CONVERT(varchar, DATEPART(month, titlStreaming)) + '/' + CONVERT(varchar, DATEPART(day, titlStreaming)) + '/' + CONVERT(varchar, DATEPART(year, titlStreaming)) AS [Day], 
             COUNT(titlTitleID) AS Total 
     FROM Title
     GROUP BY DATEPART(year, titlStreaming), DATEPART(month, titlStreaming), DATEPART(day, titlStreaming)
    ) t
where [day] is not null
ORDER BY [day] DESC

答案 1 :(得分:1)

至于所有dateparts依赖于titlStreaming,titlStreaming上的where条件就足够了。

....
From Title
where titlStreaming is not null
Group by ....