我有这个代码:
SELECT tenant.scode
,tenant.sunitcode
,rtrim(tenant.sLastName) + ', ' + (tenant.sFirstName)
,charge.total
,tenant.istatus
,tenant.dtmovein
FROM tenant
LEFT OUTER JOIN (
SELECT sum(CASE
WHEN trans.itype = 6
THEN stotalamount * - 1
ELSE CASE
WHEN trans.itype = 3
THEN stotalamount * - 1
ELSE stotalamount
END
END) total
,hperson
FROM trans
where trans.itype in (6,7)
GROUP BY hperson
) charge ON tenant.hmyperson = charge.hperson
WHERE charge.total IS NOT NULL
AND charge.total <> 0
AND tenant.istatus IN (
0
,3
,4
)
and hproperty = 2396
UNION ALL
SELECT tenant.scode
,tenant.sunitcode
,rtrim(tenant.sLastName) + ', ' + (tenant.sFirstName)
,charge.total
,tenant.istatus
,tenant.dtmovein
FROM tenant
LEFT OUTER JOIN tenant t2 on (tenant.sleasefield36 = t2.scode)
LEFT OUTER JOIN (
SELECT sum(CASE
WHEN trans.itype = 6
THEN stotalamount * - 1
ELSE CASE
WHEN trans.itype = 3
THEN stotalamount * - 1
ELSE stotalamount
END
END) total
,hperson
FROM trans
where itype in (6,7)
GROUP BY hperson
) charge ON t2.hmyperson = charge.hperson
WHERE charge.total IS NOT NULL
AND charge.total <> 0
AND tenant.istatus IN (
0
,3
,4
)
and tenant.hproperty = 2396
ORDER BY total
它从某个物业中检索拖欠租金和其他款项的所有租户以及他们所欠的款项。
我的问题是其中一处房产最近已售出,所以现在我需要从以前的房产中检索其旧余额并将其添加到新房产的余额中。我基本上可以正常工作,但是两个金额(旧属性中的 1 和新属性中的 1)在我的结果中显示为两个单独的行。第一个余额金额是从第一个查询中检索的,第二个是从 UNION ALL 之后的查询中检索的。
如何使每个租户的这两行合并余额金额,以便每个租户都有一个结果行?
提前致谢!:) 让我知道是否可以提供更多详细信息