-2

I thought I could count a column and add it as a column as I can with a sum but I get an error about having to group by / having. An example of what I want...

Initial table...

 Global ID    Local ID   Name       Role
 100          1          Andy       Manager
 100          2          Andy       Manager
 100          1          John       Co-Manager
 200          1          Andy       Co-Manager
 200          2          John       Manager
 200          2          Mike       Manager

I then want to add a column that counts the number of Manager in each group / local pairing...

 Global ID    Local ID   Name       Role         Manager Count
 100          1          Andy       Manager      1
 100          2          Andy       Manager      1    
 100          1          John       Co-Manager   0
 200          1          Andy       Co-Manager   0
 200          2          John       Manager      2
 200          2          Mike       Manager      2

I tried just joining the two tables on the global / local ID and then adding a column for count of the Role. The problem is that I get an error about grouping / having by but I don't want to group anything. I just want to add the column and still have the same number of rows. Any way around this?

FYI - for the last two rows, the last column has 2 because John and Mike are on the same group / local ID

4

1 回答 1

1

看起来您对组的定义是 [global_id, local_id] 的唯一组合。如果是这种情况,您确实想要group by这两个值,并计算角色所在的位置Manager。但是因为您想要原始表中的其他列,您必须在内联视图中进行计数,然后连接回原始表,如下所示:

select t.*, v.mgr_in_grp
  from tbl t
  left join (select global_id, local_id, count(*) as mgr_in_grp
               from tbl
              where role = 'Manager'
              group by global_id, local_id) v
    on t.global_id = v.global_id
   and t.local_id = v.local_id

小提琴: http ://sqlfiddle.com/#!2/fb3ace/2/0

请注意,与您的预期输出相比,第 3 行存在差异。

约翰,global_id 和 local_id 100 和 1 的联合经理,分别属于在该组合中具有经理的一对(安迪,你的第一行)。所以出现的计数应该是 1。

于 2015-01-30T03:23:18.827 回答