你好朋友我有2张表,如下面
tab_a --> "unit_info_id" ,"unit_id" ,"p_id" ,"p_bathroom" ,"p_bedroom" ,"p_size" ,"p_rent" ,"p_isrent" ,"u_note" ,"r_id" , "isactive"
tab_b--> "rent_id" ,"unit_info_id" ,"t_id" ,"rent_amount" ,"rent_note" ,"rent_date" ,"rent_time" , "r_id"
我的查询如下
SELECT a.* ,
(SELECT SUM(rent_amount)
FROM tab_b
LEFT JOIN tab_a ON tab_b.unit_info_id = tab_a.unit_info_id
WHERE tab_b.rent_date
between '2015-02-03' and '2015-12-03'
GROUP BY tab_b.unit_info_id
) AS "TotalIncome"
FROM tab_a a ,tab_b b
WHERE a.r_id=1 group by a.unit_info_id
当我运行上面的查询时,它给了我totalIncome别名的重复值,如下图所示
根据我目前的数据,我只有 unit_id = 1 的rent_amount, unit_id = 2 和 unit_id = 3 没有任何我的 tab_2 表中的数据,但是当我运行上面的查询时,它给了我输出类似上面的图像我需要totalIncome按照特定的单位,所以我知道如何解决它?
修改
Tab_a内容 Tab_b hasnt
答案 0 :(得分:0)
这是因为您将SUM添加为一个额外的行,因此SUM总是以TotalIncome的形式出现,因为您是GROUP BY ID。你期待什么行为?
好的,我起初并没有得到你。你必须重写那个SELECT。你可以像使用tab_a一样发布tab_b的内容吗?检查是否有效
SELECT tab_a.*, SUM(tab_b.rent_amount) AS TotalIncome FROM tab_a INNER JOIN tab_b ON tab_b.unit_info_id=tab_a.unit_info_id WHERE tab_b.rent_date between '2015-02-03' AND '2015-12-03' AND tab_a.r_id='1' GROUP BY tab_a.unit_info_id
另请注意,您最初发布的内容存在拼写错误。