其他公司数量

时间:2015-10-09 06:39:28

标签: sql

Table
Director    DirectorId  Company     CompanyID   Recordtime
Philip            66    AVEVA GROUP     15         1
Philip            66    AVEVA GROUP     15         1
Philip            66    BALFOUR BEATTY  36         1
Philip            66    BHP BILLITON    40         2
Philip            66    BHP BILLITON    40         2
 OutPut like this
Director    DirectorId  Company     CompanyID   Count
Philip            66    AVEVA GROUP     15         1
Philip            66    AVEVA GROUP     15         1
Philip            66    BALFOUR BEATTY  36         1
Philip            66    BHP BILLITON    40         0
Philip            66    BHP BILLITON    40         0

在此表中记录时间1有两个公司,记录时间2有一个 company .i需要记录时间中计数1的输出1记录时间2中的计数0因为 记录时间1第一家公司是默认公司,毕竟这是条件

2 个答案:

答案 0 :(得分:0)

您可以尝试以下内容:

select t1.*, t2.cCount from Table1 t1 join 
(select Recordtime, (count(CompanyId) - 1) as cCount from (select distinct CompanyID, Recordtime from Table1) t
group by Recordtime) t2 on t1.Recordtime = t2.Recordtime

看看这个sample fiddle

答案 1 :(得分:0)

这适用于您的情况:

SELECT v.director,
       v.directorId,
       v.company,
       v.companyId,
       CASE WHEN v.cnt > 1 THEN v.cnt - 1
            ELSE 0 END AS cnt
FROM (SELECT t.director,
             t.directorId,
             t.company,
             t.companyId,
             COUNT(DISTINCT t.company) as cnt
      FROM yourtable t
      GROUP BY t.director,
               t.directorId,
               t.company,
               t.companyId) v