Sum查询在sqlite中没有得到正确的输出

时间:2015-03-23 09:18:16

标签: android mysql sqlite sum

朋友您好我有3张如下表:

property_master -->p_id, p_name,r_id

transction_master -->t_id,p_id,amount,user_cat_id,r_id

user_trans_cat-->user_cat_id,cat_name,trans_id ,r_id

我的查询如下

SELECT property_master.p_id AS "Product Code",
   property_master.p_name AS "Description",
   (SELECT SUM(amount)
    FROM transction_master ,property_master

   JOIN user_trans_cat ON transction_master.user_cat_id = user_trans_cat.user_cat_id
   WHERE user_trans_cat.trans_id =1 and transction_master.date between   '2015-01-01' and '2015-12-31'
   group by property_master.p_id
   ) AS "Income",
   (SELECT SUM(amount)
    FROM transction_master ,property_master

   JOIN user_trans_cat ON transction_master.user_cat_id = user_trans_cat.user_cat_id
    WHERE user_trans_cat.trans_id =2 and transction_master.date between   '2015-01-01' and '2015-12-31'
   group by property_master.p_id
   ) AS "Expense"
   FROM property_master   ,transction_master where  property_master.r_id = 1

   Group by property_master.p_id

交易表 enter image description here

输出 enter image description here 我希望总收入,费用价值按照原则明智但是当我在查询之上运行它会给我所有财产的总收入价值任何想法我怎么能解决它?

2 个答案:

答案 0 :(得分:1)

下面怎么样 -

select
pm.p_id AS "Product Code",
pm.p_name AS "Description",
sum( case when utrc.trans_id =1 then tm.amount else 0 end ) as "Income",
sum( case when utrc.trans_id =2 then tm.amount else 0 end ) as "Expense"
from transction_master tm
join property_master pm on pm.p_id = tm.p_id
join user_trans_cat utrc on utrc.user_cat_id = tm.user_cat_id
where 
tm.date between   '2015-01-01' and '2015-12-31'
group by 
pm.p_id
  

更新:如果您需要列出所有属性,即使它们是   不在事务主数据中,那么您需要更改要选择的查询   从property_master然后左连接

from property_master pm
left join transction_master tm on pm.p_id = tm.p_id
left join user_trans_cat utrc on utrc.user_cat_id = tm.user_cat_id

现在左边连接条件只是内部连接,所以where条件需要作为连接条件移动,以便查询变为

select
pm.p_id AS "Product Code",
pm.p_name AS "Description",
sum( case when utrc.trans_id =1 then tm.amount else 0 end ) as "Income",
sum( case when utrc.trans_id =2 then tm.amount else 0 end ) as "Expense"
from property_master pm
left join transction_master tm on pm.p_id = tm.p_id
and tm.date between   '2015-01-01' and '2015-12-31'
left join user_trans_cat utrc on utrc.user_cat_id = tm.user_cat_id 
group by 
pm.p_id

答案 1 :(得分:0)

你可以尝试这个伴侣:

SELECT
    pm.p_id 'Product Code',
    pm.p_name 'Description',
    SUM(CASE WHEN utc.r_id = 1 THEN tm.amount ELSE 0 END) 'Income',
    SUM(CASE WHEN utc.r_id = 2 THEN tm.amount ELSE 0 END) 'Expense'
FROM
    transction_master tm
    JOIN property_master pm ON tm.p_id = pm.p_id
    JOIN user_trans_cat utc ON utc.trans_id = tm.t_id
WHERE
    tm.date BETWEEN '2015-12-31' AND '2015-01-01'
GROUP BY
    pm.p_id;