0

我有两个表 tbl_product 和 tbl_sales。我的问题是我如何从两个不同的表中获取数据并水平显示它并对 tbl_rsales 的“总计”和“折扣”求和。例如

    the ff data in my tbl_products are

    id|pcode|pdesc    |
    1 |1000 |wire     |
    2 |1443 |capactor |

    and the ff data in my tbl_sales are

    id|total|discount| pcode |
    1 |1000 |10      | 1000  |
    2 |2000 |20      | 1443  |
    3 |1000 |10      | 1000  |
    4 |1000 |20      | 1443  |

预期的输出必须是这样的。我如何从两个不同的表中选择它?

    id | pcode | pdesc     | total | discount |
    1  | 1000  | wire      | 2000  | 20       |
    2  | 1443  | capacitor | 3000  | 40       |
4

6 回答 6

0

也试试这个:

SELECT 
    tbl_products.*, 
    SUM(tbl_sales.total) as total, 
    SUM(tbl_sales.discount) as discount
FROM tbl_products,tbl_sales 
where tbl_sales.pcode = tbl_products.pcode
GROUP BY pcode
ORDER BY total ASC
于 2013-08-27T14:50:51.423 回答
0

这可以通过简单的JOINand来完成GROUP BY

SELECT
    p.id,
    p.pcode,
    p.pdesc,
    SUM(s.total) AS total,
    SUM(t.discount) AS discount
FROM 
    tbl_products AS p
LEFT JOIN 
    tbl_sales AS s ON
        s.pcode = p.pcode
GROUP BY
    p.pcode
ORDER BY
    /* your call */
于 2013-08-27T14:38:49.147 回答
0

使用这样的连接:

SELECT * FROM tbl_products INNER JOIN tbl_sales ON tbl_sales.pcode = tbl_products.pcode ORDER BY tbl_products.pcode

这将使它成为一张桌子。

于 2013-08-27T14:29:58.767 回答
0

尝试这个:

SELECT P.id, P.pcode, P.pdesc, COALESCE(SUM(S.total),0), COALESCE(SUM(s.discount),0)
FROM tbl_products P
LEFT OUTER JOIN tbl_sales S
ON P.pcode = S.pcode
GROUP BY P.id, P.pcode, P.pdesc
于 2013-08-27T14:28:42.570 回答
0

这个?

SELECT 
    tbl_products.*, 
    SUM(tbl_sales.total) as total, 
    SUM(tbl_sales.discount) as discount
FROM tbl_products 
LEFT JOIN tbl_sales ON tbl_sales.pcode = tbl_products.pcode
GROUP BY pcode
ORDER BY total ASC
于 2013-08-27T14:29:26.493 回答
0
select p.id,p.pcode,p.desc,sum(s.sales),sum(s.discount)
from tbl_products p, tbl_sales s
where p.id = s.id
group by p.id,p.pcode,p.desc;
于 2013-08-27T14:43:20.947 回答