通过sqlite数据库在多个表中进行SUM查询

时间:2014-11-13 07:12:56

标签: android sqlite select group-by sum

朋友您好我有三张桌子 property_master rent_master expense_master ,字段如下

property_master - > p_id,p_name

rent_master - > R_ID,P_ID,r_amount

expense_master - > E_ID,P_ID,e_amount

我希望r_amount和e_amount的总和与单个查询,所以我的查询如下

   SELECT p.p_id AS "Product Code",
   p.p_name AS "Description", 
   SUM(CASE WHEN ri.r_amount IS NULL THEN 0 ELSE ri.r_amount END) AS "Quantity" ,
   SUM(CASE WHEN d.e_amount IS NULL THEN 0 ELSE d.e_amount END) AS "DQuantity" 
   FROM property_master AS p
   LEFT JOIN rent_master AS ri ON ri.p_id = p.p_id
   LEFT  JOIN expense_master AS d ON d.p_id = p.p_id
   GROUP BY p.p_id
   ORDER BY SUM(ri.r_amount) DESC,
   SUM(d.e_amount) DESC

当我运行上面的代码时,它会为 r_amount 提供正确的值,但对于 e_amount ,它会为此提供双倍值,所以我知道如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果有两个rent_master行具有相同的p_id值,则每个匹配的expense_master行会得到两个连接的行。

您必须使用独立子查询计算总和:

SELECT p_id AS "Product Code",
       p_name AS "Description",
       (SELECT SUM(r_amount)
        FROM rent_master
        WHERE p_id = property_master.p_id
       ) AS "Quantity",
       (SELECT SUM(e_amount)
        FROM expense_master
        WHERE p_id = property_master.p_id
       ) AS "DQuantity"
FROM property_master
ORDER BY Quantity DESC,
         DQuantity DESC