在我的查询中多次调用sum操作,因此B2_ESTOQUE列中显示的结果变得不一致,可能原因是在select和left join操作中返回的记录数量。这是一个假设。
下面的查询中是否有错误?左连接操作是否使用不正确?
SELECT
SB1.B1_FILIAL, SB1.B1_COD, SB1.B1_DESC, SB1.B1_TIPO, SB1.B1_UM, SB1.B1_SEGUM, SB1.B1_GRUPO, SB1.B1_CONV, SB1.B1_TIPCONV, SB1.B1_PRV1,
SB1.B1_PESO, SB1.B1_CODBAR, SB1.B1_QE, SB1.B1_MSBLQL, SB1.D_E_L_E_T_, SB1.R_E_C_N_O_, SB1.MD5, SB1.DATA_UPDATE,
(SELECT BM_DESC FROM PADRAO.PORTAL_SBM001 WHERE BM_GRUPO = SB1.B1_GRUPO LIMIT 0,1) as B1_GRUPO_DESCRICAO,
(SUM(IFNULL(SB2.B2_QATU, 0)) - SUM(IFNULL(SB2.B2_RESERVA, 0)) - SUM(IFNULL(SB2.B2_QPEDVEN, 0))) - SUM(IFNULL(SC6.C6_QTDVEN, 0)) AS B2_ESTOQUE
FROM PADRAO.PORTAL_SB1001 SB1
LEFT JOIN PADRAO.PORTAL_SB2001 SB2
ON SB1.B1_COD = SB2.B2_COD
LEFT JOIN PADRAO.PORTAL_SC6001_NEW SC6
ON SB1.B1_COD = SC6.C6_PRODUTO
AND (SC6.C6_NUM IS NULL OR SC6.C6_NUM = '')
AND SB2.B2_LOCAL IN ('07','08')
WHERE (SB1.D_E_L_E_T_ IS NULL OR SB1.D_E_L_E_T_ = '')
AND (SB2.D_E_L_E_T_ IS NULL OR SB2.D_E_L_E_T_ = '')
AND (SC6.D_E_L_E_T_ IS NULL OR SC6.D_E_L_E_T_ = '')
AND (SB1.B1_MSBLQL IS NULL OR SB1.B1_MSBLQL <> '1')
GROUP BY SB1.B1_COD;
答案 0 :(得分:2)
我不确定所有的检查是否仍然无效。&#39;&#39;&#39;是在哪里的条款。我使用coalesce将null更改为空字符串并删除子查询where子句中的值而不是最外层where子句中的值;但也许你想保持左连接Nulls,这就是你检查清空字符串和null的原因......
然而,这就是我作为UNTESTED查询所拥有的内容。注意我转换了两个左连接表,以便通过连接键对连接和组之前的值求和。
SELECT
SB1.B1_FILIAL
, SB1.B1_COD
, SB1.B1_DESC
, SB1.B1_TIPO
, SB1.B1_UM
, SB1.B1_SEGUM
, SB1.B1_GRUPO
, SB1.B1_CONV
, SB1.B1_TIPCONV
, SB1.B1_PRV1
, SB1.B1_PESO
, SB1.B1_CODBAR
, SB1.B1_QE
, SB1.B1_MSBLQL
, SB1.D_E_L_E_T_
, SB1.R_E_C_N_O_
, SB1.MD5
, SB1.DATA_UPDATE
,(SELECT BM_DESC FROM PADRAO.PORTAL_SBM001 WHERE BM_GRUPO = SB1.B1_GRUPO LIMIT 0,1) as B1_GRUPO_DESCRICAO
, SB2.mSum - SB6.mSUM as B2_ESTOQUE
FROM PADRAO.PORTAL_SB1001 SB1
LEFT JOIN (SELECT SB2.B2_COD, SUM(IFNULL(B2_QATU, 0) - IFNULL(B2_RESERVA, 0) - IFNULL(B2_QPEDVEN, 0)), AS mSum
FROM PADRAO.PORTAL_SB2001
WHERE B2_LOCAL IN ('07','08')
AND coalesce(SB2.D_E_L_E_T_,'')=''
GROUP BY SB2.B2_COD) SB2
ON SB1.B1_COD = SB2.B2_COD
LEFT JOIN (SELECT SUM(IFNULL(SC6.C6_QTDVEN, 0)) mSUM, C6_PRODUTO
FROM PADRAO.PORTAL_SC6001_NEW SC6
WHERE coalesce(SC6.C6_NUM,'') = ''
AND coalesce(SC6.D_E_L_E_T_,'') = ''
GROUP BY C6_PRODUTO)
ON SB1.B1_COD = SC6.C6_PRODUTO
WHERE (SB1.D_E_L_E_T_ IS NULL OR SB1.D_E_L_E_T_ = '')
AND (SB1.B1_MSBLQL IS NULL OR SB1.B1_MSBLQL <> '1')
GROUP BY SB1.B1_COD;