在SQL中使用GROUP BY检查条件

时间:2016-10-06 14:19:56

标签: sql sql-server-2008 group-by case conditional-statements

如何有效地检查组中是否存在至少一条记录。如果满足两个条件,那么我想在结果中得到它。

我现在在第一步

select 
worker,
,help_column_A=sum(case when condition='A' then 1 else 0 end)
,help_column_B=sum(case when condition='B' then 1 else 0 end)
from table
group by
worker

然后在第二步我做:

select 
case when help_column_A>0 and when help_column_B>0 then 'A and B'
case when help_column_A>0 then 'A'
case when help_column_B>0 then 'B'
end

数据是一个很大的集合,我绝对不需要计算A或B来获得最终的预期结果。

以下是示例数据:

表格

+-----------+------------+
| worker    | condition  |
+-----------+------------+
| 1         | A          |
+-----------+------------+
| 1         | A          |
+-----------+------------+
| 1         | B          |
+-----------+------------+
| 1         | B          |
+-----------+------------+
| 2         | A          |
+-----------+------------+
| 2         | A          |
+-----------+------------+
| 2         | A          |
+-----------+------------+
| 3         | B          |
+-----------+------------+
| 3         | B          |
+-----------+------------+
| 3         | B          |
+-----------+------------+

期望的结果

+-----------+------------+
| worker    | text field |
+-----------+------------+
| 1         | A and B    |
+-----------+------------+
| 2         | A          |
+-----------+------------+
| 3         | B          |
+-----------+------------+

表中的条件可以评估为A,B和C等多个案例。在示例中,我只使用了A和B.

3 个答案:

答案 0 :(得分:2)

这是你想要的吗?

select worker,
       (case when min(condition) = max(condition) then max(condition)
             else 'A and B'
        end) from table
where condition in ('A', 'B')
group by worker;

where条件可能没有必要,但您似乎只关注As和Bs。

更一般地说,你可以这样做:

select worker,
       (case when min(condition) = max(condition) then max(condition)
             else min(condition) + ' - ' + max(condition)
        end) from table
group by worker;

答案 1 :(得分:1)

您希望将不同的condition聚合为字符串。我假设您的条件不包含禁止的XML字符和&或者<。 (否则会慢一些。)

declare @t table (
   worker int, 
   condition varchar(10)
);
insert @t values
 (1,'A')
,(1,'A')
,(1,'A')
,(1,'A')
,(2,'B')
,(2,'B')
,(2,'B')
,(3,'C')
,(3,'A')
,(3,'B');

select worker,
    conditions=stuff((select distinct ' and ' + t2.condition 
        from @t t2 
        where t2.worker = t1.worker
        order by ' and ' + t2.condition
        for xml path('')),1,5,'') 

from @t t1
group by worker ;  

答案 2 :(得分:0)

如果要应用WHERE子句来汇总要使用的数据Having

  

指定组或聚合的搜索条件。可以   仅用于SELECT语句。 HAVING通常用于   GROUP BY子句。当不使用GROUP BY时,HAVING的行为类似于   WHERE子句。

即:

SELECT
    worker,
    ,help_column_A=sum(case when condition='A' then 1 else 0 end)
    ,help_column_B=sum(case when condition='B' then 1 else 0 end)
FROM table
GROUP BY
    worker
HAVING
    sum(case when condition='A' then 1 else 0 end) > 0
    OR sum(case when condition='B' then 1 else 0 end) > 0