如何实现" Foo只有一个Bar与Foo相关联的次数"

时间:2016-09-20 21:08:21

标签: sql sql-server tsql

我的情况是这样的。我有一张像

这样的表格
 Foo | Bar | ... |
==================
  A  |  1  | ... |
  A  |  2  | ... |
  A  |  2  | ... |  
  B  |  2  | ... |
  B  |  2  | ... |
  B  |  1  | ... |
  C  |  1  | ... |     
  C  |  1  | ... |  
  C  |  1  | ... |  
  D  |  2  | ... |  
  D  |  1  | ... | 
  D  |  1  | ... |

以及我想要的查询,用英语,

  

"对于每个Bar,获取与该Foo相关联的Bar个数   仅Bar | Count | ============= 1 | 1 | 2 | 0 | "

所以结果表就像

  C  |  1  | ... |     
  C  |  1  | ... |  
  C  |  1  | ... | 

说明:

你可以看到行

Foo

是给定Bar仅与一个for相关联的示例,但没有其他此类示例。

这是我面临的现实场景的通用版本,我无法弄清楚如何解决它。

1 个答案:

答案 0 :(得分:1)

嗯。你只关心只有一个酒吧的foos。这就是:

select foo, min(bar) as bar
from t
group by foo
having min(bar) = max(bar)

然后,如果你想要条数。 。 。让我假设你有一个条形列表:

select b.bar, coalesce(bb.cnt, 0)
from bars b left join
     (select bar, count(*) as cnt
      from (select foo, min(bar) as bar
            from t
            group by foo
           ) fb
      group by bar
     ) bb
     on b.bar = bb.bar;

如果您没有条形列表,请在(select distinct bar from t) bar子句中使用bar代替from

我认为这也有效:

select bar,
       count(distinct case when minbar = maxbar then foo end) as numfoos
from (select t.*, min(bar) over (partition by foo) as minbar,
             max(bar) over (partition by foo) as maxbar
      from t
     ) t
group by bar;