我想计算3个表中的几个项目:
以下示例数据:
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。
答案 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)