我将举例说明我所拥有的桌子
Supplier | Value
sup1 | 4
sup2 | 1
sup1 | 0
sup1 | 3
sup2 | 5
我需要一个可以按供应商求平均值的结果,但是如果供应商的值为0,请不要求平均值,而应返回0
它应该像这样:
Supplier | Value
sup1 | 0
sup2 | 3
答案 0 :(得分:4)
这是一个小技巧,但它应该可以工作:
SELECT Supplier,
CASE WHEN MIN(ABS(Value)) = 0 THEN 0 ELSE AVG(Value) END
FROM TableTest
GROUP BY Supplier
编辑:使用ABS()函数可以避免出现负值问题
答案 1 :(得分:2)
DECLARE @TAB TABLE (SUPPLIER VARCHAR(50),VALUE INTEGER)
INSERT INTO @TAB
SELECT 'sup1',4
UNION ALL
SELECT 'sup2',1
UNION ALL
SELECT 'sup1',0
UNION ALL
SELECT 'sup1',3
UNION ALL
SELECT 'sup2',5
SELECT * FROM @TAB
SELECT T1.SUPPLIER,CASE WHEN EXISTS(SELECT 1 FROM @TAB T WHERE T.SUPPLIER = T1.SUPPLIER AND T.VALUE = 0) THEN 0 ELSE AVG(T1.VALUE) END AS VALUE
FROM @TAB T1
GROUP BY T1.SUPPLIER
结果
SUPPLIER VALUE
sup1 0
sup2 3
答案 2 :(得分:1)
使用以下查询是一种方法。
首先,我推入Value = 0的供应商,然后根据结果,我将执行剩余的计算,最后使用UNION获得预期结果:
DECLARE @ZeroValue TABLE (Supplier VARCHAR (20));
INSERT INTO @ZeroValue (Supplier)
SELECT Supplier FROM TestTable WHERE Value = 0
SELECT Supplier, 0 AS Value FROM @ZeroValue
UNION
SELECT T.Supplier, AVG(T.Value) AS Value
FROM TestTable T
JOIN @ZeroValue Z ON Z.Supplier != T.Supplier
GROUP BY T.Supplier
用于示例的模式:
CREATE TABLE TestTable (Supplier VARCHAR (20), Value INT);
INSERT INTO TestTable (Supplier, Value) VALUES
('sup1', 4), ('sup2', 1), ('sup1', 0), ('sup1', 3), ('sup2', 5);