SQL中的SUM的AVG

时间:2014-04-07 13:31:12

标签: sql

这是我的代码:

SELECT B1_COD, SB1030.B1_DESC, B2_CM1, B2_QATU, SUM (B2_QATU)
FROM SB1030 
INNER JOIN SB2030 ON B1_COD = B2_COD
WHERE (B1_TIPO='PA') AND (B2_QATU <> '0')

我想:

  • b2_cm1乘以b2_qatu创建b2_VAL
  • 将所有b2_qatu与创建b1_cod
  • b2_SAL相同
  • b2_VAL除以b2_SAL

任何人都可以帮助我?????

由于

2 个答案:

答案 0 :(得分:1)

以下是我认为您正在寻找的内容。带有和的b1_cods列表和基于总和的计算。

select 
  b1_cod, 
  sb1030.b1_desc, 
  sum(b2_cm1) as sum_cm1, 
  sum(b2_qatu) as b2_sal, 
  sum(b2_qatu * b2_cm1) as b2_val,
  sum(b2_qatu) / sum(b2_qatu * b2_cm1) as new_field
from sb1030 
inner join sb2030 on b1_cod = b2_cod
where b1_tipo = 'pa' and b2_qatu <> '0'
group by b1_cod, sb1030.b1_desc
order by b1_cod, sb1030.b1_desc;

答案 1 :(得分:0)

您是否只想要结果b2_VAL和b2_SAL?

尝试使用WITH CTE:

 WITH CTE AS(
 SELECT SUM(B1_COD) AS B1_COD, SB1030.B1_DESC,B2_CM1*B2_QATU AS b2_VAL, SUM (B2_QATU) AS  B2_QATU
 FROM SB1030 
 INNER JOIN SB2030 ON B1_COD = B2_COD
 WHERE (B1_TIPO='PA') AND (B2_QATU <> '0'))
 SELECT B1_COD+B2_QATU, b2_VAL
 FROM CTE

这是你想要的吗?