根据组值返回ID

时间:2017-10-05 22:26:44

标签: sql sql-server sql-server-2012 subquery

表t1的样本子集

+----+------+
| ID | Flag |
+----+------+
|  1 |    1 |
|  1 |    0 |
|  1 |    0 |
|  2 |    0 |
|  2 |    0 |
|  2 |    0 |
|  3 |    1 |
|  3 |    1 |
|  3 |    0 |
+----+------+

我需要以两种不同的方式基于Flag值提取ID:

1)所有ID在Flag中没有1。

    +----+
    | ID |
    +----+
    |  2 |
    +----+

2)所有ID都有一个以上1的标记。

    +----+
    | ID |
    +----+
    |  3 |
    +----+

尝试查询无用,因此排除了

4 个答案:

答案 0 :(得分:1)

实现此目的的一种简单方法是使用案例聚合。例如:

DECLARE @T TABLE (ID INT, Flag BIT);
INSERT @T VALUES (1, 1), (1, 0), (1, 0), (2, 0), (2, 0), (2, 0), (3, 1), (3, 1), (3, 0);

SELECT ID
FROM @T
GROUP BY ID
HAVING COUNT(CASE WHEN Flag = 1 THEN 1 END) = 0; -- No flag 1.

SELECT ID
FROM @T
GROUP BY ID
HAVING COUNT(CASE WHEN Flag = 1 THEN 1 END) > 1; -- More than one flag 1.

答案 1 :(得分:1)

这是一个特殊情况的代码,因为标志是数字,是1或0。

SELECT ID,
    CASE
        WHEN Ones = 0
            Then 'No active flags'
        When Ones > 1 
            Then 'Multiple Active flags'
    END
FROM (
    SELECT ID,
       Sum(Cast(Flag as int)) as Ones 
    FROM t1
    GROUP BY ID 
    ) as Src
WHERE Ones != 1

答案 2 :(得分:0)

使用以下查询检查标志总数。

1)

SELECT id,
       SUM(flag) cnt
  FROM t1  
 GROUP BY id
HAVING SUM(flag) = 0

结果

id  cnt
2   0

2)

SELECT id,
       SUM(flag) cnt
  FROM t1  
 GROUP BY id
HAVING SUM(flag) > 1

结果

id  cnt
3   2

答案 3 :(得分:0)

只要您的标志是数字且只有值1和0,那么您可以使用以下两个查询:

select ID from t1 group by ID having sum(cast(flag as int)) = 0;

select ID from t1 group by ID having sum(cast(flag as int)) > 1;