我可以在SQL Server中计算某个场景吗?

时间:2016-06-27 00:13:52

标签: sql sql-server sql-server-2014

我的表格看起来像这样

ID | I  | II | III | IV | V  |
===============================
1  | 1  | 0  | NULL|NULL|NULL|
2  |NULL|NULL|NULL | 0  |  1 |
3  | 1  |  0 |  0  |NULL|NULL|
4  |NULL|NULL|NULL |NULL| 1  |
.    .     .    .    .    .
.    .     .    .    .    .  
.    .     .    .    .    .

我正在使用SQL Server 2014。

我希望计算具有#1和#3等场景的ID数量。有查询可以做到吗?谢谢!

3 个答案:

答案 0 :(得分:0)

我猜测当你编写#em>#1和#3 这样的场景时,你的意思是想要计算值等于第1行或第3行有。如果是这样的话,你会做这样的事情。

select count(*)
from YourTable
where (I = 1
        and II = 0
        and III is null
        and IV is null
        and V is null)
    or (I = 1
        and II = 0
        and III = 0
        and IV is null
        and V is null);

或者,您可以将上述查询简化为以下形式:

select count(*)
from YourTable
where (I = 1
        and II = 0
        and (III = 0 or III is null)
        and IV is null
        and V is null);

也许这就是你正在寻找的东西:

select *
from YourTable
where coalesce(I, II, III, IV, V) is not null;

或者这个:

select
    ValidCnt = sum(case
        when coalesce(I, II, III, IV, V) is not null then 1
        else 0
        end),
    InvalidCnt = sum(case
        when coalesce(I, II, III, IV, V) is null then 1
        else 0
        end)
from YourTable;

答案 1 :(得分:0)

从YourTabel中选择COUNT(ID)WHERE ISNULL(I,-1)!= - 1

说明:我是你的专栏名称&您可以在where条件中指定更多列。

答案 2 :(得分:0)

希望这有帮助,

CREATE TABLE Joe ( ID INT , I int NULL, II int NULL, III int NULL, IV int NULL, V int NULL)

INSERT INTO Joe VALUES (1, 1, 0, NULL, NULL, NULL)
INSERT INTO Joe VALUES (2, NULL, NULL, NULL, 0, 1)
INSERT INTO Joe VALUES (3, 1, 0, 0, NULL, NULL)
INSERT INTO Joe VALUES (4, NULL, NULL, NULL, NULL, 1)

-- SELECT * FROM Joe

SELECT J.* FROM Joe J
JOIN
  ( SELECT J.ID,Count(0) Counter FROM Joe J WHERE J.I IS NOT NULL
     AND J.V IS NULL
   GROUP BY J.Id) JoeCounts ON J.Id = JoeCounts.Id