3

加入 2 个表后,我无法获取 sum(),其中一个是 HEADER AND DETAIL。它只为下面的 sql 语句提供 0 结果。需要一些帮助:

我的桌子:

INVHDR:

    Invno,  Invdate,   Ac_code
    100     2013-04-01  2
    101     2013-04-30  2

    INVDTLS:
    Invno,  Prod_desc, Amount
    100     Argon      155
    100     Argon      250
    101     Oxygen     322
    101     Oxygen     065

期望的结果:amts 的总和:405

MYSQL 语句到内部连接和 sum()

SELECT
        a.Invno, a.Ac_code, a.Invdate, b.*
    FROM INVHDR a
    INNER JOIN (
        SELECT
                Invno, Prod_desc, SUM( Amount ) AS amts
            FROM INVDTLS
            WHERE Prod_desc='Argon'
        ) AS b ON a.Invno = b.Invno
    WHERE
        a.Ac_code='2'
        AND a.Invdate BETWEEN '2013-04-01'
        AND '2013-04-30'
    GROUP BY a.Ac_code
4

2 回答 2

1

为什么要写这么复杂 Query的,试试这个:

SELECT sum(b.Amount)
FROM INVHDR a 
INNER JOIN INVDTLS b
ON a.Invno = b.Invno 
WHERE a.Ac_code='2' 
AND a.Invdate BETWEEN '2013-04-01' AND '2013-04-30' 
AND b.Prod_desc='Argon'
--Group by b.Prod_desc,a.Invno, a.Ac_code

这是SQL 小提琴

于 2013-04-23T12:05:13.417 回答
-1

检查http://www.sqlfiddle.com/#!2/86377/8 谢谢@Luv

SELECT 
    a.Invno, a.Ac_code, b.Prod_desc, SUM(b.Amount) AS Amount
FROM INVHDR a 
INNER JOIN INVDTLS b ON a.Invno = b.Invno 
WHERE 
    a.Ac_code = 2 -- a.Ac_code='2'
    AND a.Invdate BETWEEN '2013-04-01' AND '2013-04-30' 
    AND b.Prod_desc='Argon'
group by a.Invno, a.Ac_code, b.Prod_desc
于 2013-04-23T12:04:45.270 回答