我正在尝试执行SUM函数,但我只希望它在所有字段都不为空时返回值。现在,当它执行SUM时,它会跳过NULL值并只添加非空值。我想要发生的是,即使一个值在总和中为空,它也只是返回null。这是一个示例表:
Table_1
-------------
Price Quant
10.00 | NULL
11.00 | 100
这是我正在运行的查询:
SELECT SUM((Price * Quant)) FROM [Table_1]
此时,它返回值1100.我希望它返回NULL,因为第一个记录的Price * Quant
为空。
答案 0 :(得分:2)
您可以执行以下操作:
Select
case when count(
case when price + quant is null then 1 end
) = 0 then sum(price*quant) end as val
From your_table;
我们正在检查price + quant是否为null因为null + anything为null,如果price或quant为null,它将返回null。你当然可以使用其他算术运算,但我认为总和是最轻的。
您也可以单独检查:
Select
case when count(
case when price is null or quant is null then 1 end
) = 0 then sum(price*quant) end as val
From your_table;
答案 1 :(得分:0)
SELECT SUM((Price * Quant)) FROM [Table_1]
WHERE Price IS NOT NULL WHERE Quant IS NOT NULL
您可以运行此脚本
答案 2 :(得分:0)
我会这样做......
SELECT
CASE
WHEN MAX(T2.NoValue) IS NOT NULL
THEN NULL
ELSE SUM(Price * Quant)
END AS Total
FROM Table_1 T1
LEFT JOIN
(
SELECT TOP 1 1 AS NoValue
FROM Table_1
WHERE Quant IS NULL
OR Price IS NULL
) T2
ON NoValue = 1
;
答案 3 :(得分:0)
这样怎么样:
SELECT case when Quant is null then null else SUM((Price * Quant)) as this_sum end FROM [Table_1]
答案 4 :(得分:0)
如果要测试Price和Quant的空值,可以使用以下内容:
-- Sample T-SQL schema to demonstrate the SQL query
DECLARE @tb TABLE
(
Price INT NULL,
Quant INT NULL
)
INSERT INTO @tb(price, quant) VALUES (10, null)
INSERT INTO @tb(price, quant) VALUES (20, 100)
IF EXISTS(SELECT 1 FROM @tb WHERE (price + quant) IS NULL)
SELECT NULL AS C
ELSE
SELECT SUM(price * quant) AS C
FROM @tb
如果您只需要测试定量,则使用“quant”替换“(price + quant)”。