根据同一组中的列总和,在SQL中缩放特定的行值

时间:2015-02-17 13:07:38

标签: sql sql-server

我希望有人可以帮助我,因为我无法找到解决方案

我对生产线中的生产单位有以下数据:

enter image description here

对于我需要的特定班次:

SUM(Total Count Yield) - SUM(Good Count Yield) = SUM(Defect Count Yield)

所以我想的是通过满足上述公式的比例来上下缩放缺陷。 NB。如果结果超出1-2%,仍然可以接受。

找出所有缺陷应该在班次中加起来

  

D-actual =(班次的所有Good Count Yield值的总和)     - (班次的所有总收益率值的总和)

查找当前缺陷

  

D-current =(班次的所有缺陷计数产量值的总和)

因此,缩放特定班次的所有缺陷计数的比率为:

  

r = D-actual / D-current。

有人能指出我正确的方向将其写入SQL查询吗?

编辑:

因此,对于先前数据中的Shift 1,缺陷计数应为:

  

Total_SUM(100 + 100 + 300) - Good_SUM(100 + 150 + 100)= 150

但实际上默认计数是:

  

缺陷_SUM(220 + 240 + 200)= 660

所以我想把第1班的所有缺陷扩展到r = 150/660。例如:

  

行ID 3的产量为220 *(150/660)= 50   行ID 6的产量为240 *(150/660)= 54   行ID 9的产量为200 *(150/660)= 45

该班次的总缺陷数将为50 + 54 + 45 = 149,这在我的误差范围内。

1 个答案:

答案 0 :(得分:0)

如果没有错,您需要使用Conditional Aggregate。试试这个。

SELECT shift,
       D_actual = Sum(CASE WHEN name = 'Good Count' THEN yeild ELSE 0 END) 
                    - Sum(CASE WHEN name = 'Total Count' THEN yeild ELSE 0 END) ,
       D_Current = Sum(CASE WHEN name = 'Defect Count' THEN yeild ELSE 0 END),
       R = ( Sum(CASE WHEN name = 'Good Count' THEN yeild ELSE 0 END) 
               - Sum(CASE WHEN name = 'Total Count' THEN yeild ELSE 0 END) ) 
                      / Sum(CASE WHEN name = 'Defect Count' THEN yeild ELSE 0 END) 
FROM   yourtable
GROUP  BY shift 

或在CTEsub-select中进行更易读的分组

;WITH cte
     AS (SELECT shift,
                D_actual= Sum(CASE WHEN name = 'Good Count' THEN yeild ELSE 0 END) 
                          - Sum(CASE WHEN name = 'Total Count' THEN yeild ELSE 0 END),
                D_Current= Sum(CASE WHEN name = 'Defect Count' THEN yeild ELSE 0 END)
         FROM   yourtable
         GROUP  BY shift)
SELECT shift,
       D_actual,
       D_Current,
       r=D_actual / D_Current
FROM   cte