删除T-SQL中子查询返回的Null值

时间:2014-11-12 20:14:28

标签: sql-server tsql

我正在尝试删除结果集的空值。我正在为我的列使用子查询。我无法使用having函数删除空值。

我正在使用下面的查询,

Select 
    MONTH(Salesdate) as Month, 
    (Select sum(InvoiceSale) where year(SalesDate) = 2013) as SalesVal2013 
from 
    tblSales
Where 
    tblsales.InvoiceSale is not NUll
group by 
    Month(SalesDate)
Having 
    sum(InvoiceSale) is not null

解决方案的任何方向都非常有用。

谢谢

菲尔

3 个答案:

答案 0 :(得分:0)

我没有理由看到子查询。试试这个:

SELECT MONTH(Salesdate) AS Month, SUM(InvoiceSale) AS SalesVal2013 
FROM tblSales
WHERE tblsales.InvoiceSale IS NOT NUll
AND year(SalesDate)=2013
AND InvoiceSale IS NOT NULL
GROUP BY MONTH(SalesDate)

答案 1 :(得分:0)

我认为您希望在子选择中进行null测试,而不是在HAVING子句中,如下所示:

Select MONTH(Salesdate) as Month, (Select sum(InvoiceSale) where year(SalesDate)=2013 AND InvoiceSale IS NOT NULL) as SalesVal2013 from tblSales
group by Month(SalesDate)

答案 2 :(得分:0)

您需要HAVING中与SalesVal2013的实际计算中相同的内容

这有效..

我制作了一些样本数据。试试这个

With SalesList as 
(
          Select '1/1/2013' SalesDate, 123 InvoiceSale
    Union Select '1/1/2014' SalesDate, 123 InvoiceSale
    Union Select '2/1/2013' SalesDate,  NULL InvoiceSale
    Union Select '3/1/2013' SalesDate, 234 InvoiceSale
    Union Select '3/1/2012' SalesDate, 234 InvoiceSale
)
Select SalesDate, (Select Sum (InvoiceSale) Where Year(SalesDate)=2013) SalesVal2013
FROM SalesList 
Group by SalesDate
Having ((Select Sum (InvoiceSale) Where Year(SalesDate)=2013)) Is Not NULL

这是输出

SalesDate SalesVal2013
--------- ------------
1/1/2013  123
3/1/2013  234

(2 row(s) affected)

修改

但是,我看到你在条款中包含了MONTH(SalesDate),这在工作中引起了巨大的反响。这个改写对你有用吗?

SET ANSI_WARNINGS OFF;

With SalesList as 
(
          Select '1/1/2013' SalesDate, 123 InvoiceSale
    Union Select '1/1/2014' SalesDate, 123 InvoiceSale
    Union Select '2/1/2013' SalesDate,  NULL InvoiceSale
    Union Select '3/1/2013' SalesDate, 435 InvoiceSale
    Union Select '3/1/2013' SalesDate, NULL InvoiceSale
    Union Select '3/1/2012' SalesDate, 234 InvoiceSale
)
Select Month (SalesDate), Sum (InvoiceSale)
FROM SalesList 
Where year(SalesDate)=2013
Group by Month (SalesDate)
Having Sum (InvoiceSale) Is Not NULL

输出

----------- -----------
1           123
3           435

(2 row(s) affected)