T-SQL计算不同的行以包含唯一的零

时间:2016-06-27 09:18:59

标签: tsql

我有以下测试脚本:

DECLARE @Test TABLE (number INT)
INSERT INTO @Test VALUES (6)
INSERT INTO @Test VALUES (6)
INSERT INTO @Test VALUES (6)
INSERT INTO @Test VALUES (2)
INSERT INTO @Test VALUES (2)
INSERT INTO @Test VALUES (0)
INSERT INTO @Test VALUES (0)
INSERT INTO @Test VALUES (0)
INSERT INTO @Test VALUES (0) INSERT INTO @Test VALUES (0)
SELECT * FROM @Test
SELECT count(*) FROM @Test GROUP BY number

结果

number
6
6
6
2
2
0
0
0
0
0

(No column name)
5
2
3

我试图得到7的计数,即6和2的不同而零是唯一的?

3 个答案:

答案 0 :(得分:2)

我想出的最简单的方法是:

SELECT COUNT(DISTINCT NULLIF(Number, 0)) + SUM(CASE WHEN Number = 0 THEN 1 END)
FROM @Test

NULLIF使COUNT忽略数字等于0DISTINCT只负责计算每个数字一次,SUM使用CASE计算0条记录的数量。

答案 1 :(得分:0)

不完全确定为什么你会想要这个,但是你可以单独执行两个查询并执行UNION ALL来组合结果。

测试数据

CREATE TABLE #TestData (Number int)
INSERT INTO #TestData (Number)
VALUES
(6), (6), (6), (2), (2), (0), (0), (0), (0), (0)

查询

SELECT DISTINCT
Number
FROM #TestData
WHERE Number <> 0
UNION ALL
SELECT
Number
FROM #TestData
WHERE Number = 0

结果

Number
2
6
0
0
0
0
0

如果你想返回数字7,那么只需将它包装在这样的外部查询中;

SELECT
COUNT(1) FinalCount
FROM
(
    SELECT DISTINCT
    Number
    FROM #TestData
    WHERE Number <> 0
    UNION ALL
    SELECT
    Number
    FROM #TestData
    WHERE Number = 0
) a

结果

FinalCount
7

答案 2 :(得分:0)

试试这个:

DECLARE @Test TABLE (number INT)
INSERT INTO @Test VALUES (6), (6), (6), (2), (2), (0), (0), (0), (0) ,(0)

SELECT COUNT(DISTINCT NewNumber)
FROM (SELECT number, 
             (CASE WHEN number = 0  THEN ROW_NUMBER() OVER(ORDER BY number) * RAND()
                    ELSE number END) AS NewNumber
      FROM @Test) AS T

输出结果:

7

如果您要添加GROUP BY [number],您将收到:

number  cnt
0       5
2       1
6       1