计算3个连接表的唯一行

时间:2014-09-04 10:27:08

标签: sql sql-server tsql count

我想计算3个表中的几个项目:

  • "总计" - 批处理中的总序列号(批处理是Serialnumber的3位数字)
  • " Call_Per_Code" - 使用每个批次的callnr计算唯一代码
  • " NoCall" - 为每个批次计算没有callnr的唯一代码

以下示例数据:

Table Test1
CallNr      CallType  
1           rej  
2           rej  
3           rej  
4           rej  
5           QC  
6           QC  
7           rej  
8           rej  

Table Test2
CallNr     Code  
1          201401  
3          201402  
4          201404  
5          201401  
7          201401  
8          201401

Table Test3  
Code    PartCode  SerialNumber  
201401  68001     123-01  
201402  68001     123-02  
201403  68001     123-03  
201404  68001     124-01  
201405  68001     124-02  
201406  68001     124-03  

结果必须是:

Batch Total NoCall Call_Per_Code  
123   3     1      2  
124   3     2      1  

但我得到了结果:

Batch Total NoCall Call_Per_Code  
123   3     1      4  
124   2     1      1  

我在SQL Server 2012上使用sql代码:

SELECT
   substring(T3.SerialNumber,1,3) as batch
   ,COUNT(DISTINCT concat(T3.code,substring(T3.SerialNumber,1,3))) as Total
   ,sum(case when T2.CallNr is null then 1 else 0 end) as NoCall
   ,sum(case when T2.CallNr is null then 0 else 1 end) as Call_per_Code
FROM Test1 T1 
    INNER JOIN Test2 T2 
        ON T1.CallNr=T2.CallNr AND T1.CallType='rej' 
    RIGHT JOIN Test3 T3 
        ON T2.Code=T3.Code  
GROUP BY substring(T3.SerialNumber,1,3)

如何在Call_Per_Code列上获得正确的计数。具有CallNr的代码201401计为3而不是1。

1 个答案:

答案 0 :(得分:1)

如果从Test3开始,这个查询会变得更容易 - 如果你从那里开始,你甚至不需要加入Test1:

SELECT
   SUBSTRING(T3.SerialNumber, 1, 3) AS Batch,
   COUNT(DISTINCT T3.Code) AS Total,
   SUM(CASE WHEN T2.CallNr IS NULL THEN 1 ELSE 0 END) AS NoCall,
   COUNT(DISTINCT T2.Code) AS Call_Per_Code
FROM Test3 T3
    LEFT OUTER JOIN Test2 T2 ON T3.Code = T2.Code
GROUP BY SUBSTRING(T3.SerialNumber, 1, 3)