SQL组2个不同的表

时间:2016-12-15 15:24:50

标签: sql

我想链接到表(sum(preco)和来自客户端的名称)

 SELECT SUM(ARTIGO.PRECO) AS SUM_PRECO , CLIENTE.NOME_P
FROM CLIENTE
INNER JOIN ARTIGO
ON ARTIGO.ID IN
    (SELECT ARTIGO_ID FROM PERTENCERV2 WHERE COMPRACLIENTE_ID IN
        (SELECT ID FROM COMPRACLIENTE WHERE CLIENTE_ID IN
           (SELECT ID FROM CLIENTE )))
WHERE CLIENTE.ID IN
    (SELECT CLIENTE_ID FROM COMPRACLIENTE WHERE ID IN
        (SELECT COMPRACLIENTE_ID FROM PERTENCERV2 WHERE ARTIGO_ID IN
            (SELECT ID FROM ARTIGO)))
GROUP BY CLIENTE.NOME_P;

但上面代码的结果是

SUM_PRECO NOME_P              
    39    Joaquim             
    39    José                

和' 39'所有价格的总和 我如何隔离2个客户的帐户

i added this image hope it can help understand

1 个答案:

答案 0 :(得分:2)

您必须将ARTIGOCLIENTE表与您的图片中的JOIN相关联(请在下次将结构表放在此处,不带图片),查询将如下:

试试这个:

SELECT SUM(a.preco) AS sum_preco , c.nome_p
FROM cliente c
JOIN compracliente cc
    ON c.id = cc.cliente_id
JOIN pertencerv2 p
    ON p.compracliente_id = cc.id
JOIN artigo a
    ON a.id = p.artigo_id
GROUP BY c.nome_p

告诉我它是否正常