您正在尋找條件彙總備註此解決方案僅適用於每個財政年度的房屋詳細信息中的每個子分類(稅類型)的條目。
SELECT c.consumer_name as Name, c.house_number, c.address,
sum(CASE WHEN h.subincome = 'Garbage tax' THEN f.garbage_tax else 0 end) -
sum(CASE WHEN h.subincome = 'Garbage tax' THEN h.rupees else 0 END) as gtax,
sum(CASE WHEN h.subincome = 'House tax' THEN f.house_tax else 0 end) -
sum(CASE WHEN h.subincome = 'House tax' THEN h.rupees else 0 END) as htax,
sum(CASE WHEN h.subincome = 'Light tax' THEN f.light_tax else 0 end) -
sum(CASE WHEN h.subincome = 'Light tax' THEN h.rupees else 0 END) as LTAX
from house_details h
INNER JOIN financial_year f ON h.financial_year = f.year AND h.house_id = f.house_number
INNER JOIN consumer_details c ON h.house_id = c.house_number AND h.financial_year != '2017-2018'
group by c.consumer_name , c.house_number, c.address
結果
+------+--------------+---------+------+------+------+
| Name | house_number | address | gtax | htax | LTAX |
+------+--------------+---------+------+------+------+
| Bala | 22 | Mumbai | 450 | 145 | 710 |
+------+--------------+---------+------+------+------+
1 row in set (0.03 sec)
如果不能保證會有在每一個財政年度,則該解決方案已經從應付稅款表驅動,每subincome一個條目(財政年度)這在我看來是設計得很差,不靈活並且強制次優解決方案
select c.consumer_name as Name, s.house_number, c.address,
sum(case when subincome = 'garbage tax' then taxdue else 0 end) - sum(case when subincome = 'garbage tax' then taxpaid else 0 end) as gtax,
sum(case when subincome = 'house tax' then taxdue else 0 end) - sum(case when subincome = 'house tax' then taxpaid else 0 end) as htax,
sum(case when subincome = 'light tax' then taxdue else 0 end) - sum(case when subincome = 'light tax' then taxpaid else 0 end) as ltax
from
(
SELECT F.`house_number`, F.`year`, F.`house_tax` taxdue, F.`createdAt`, F.`updatedAt`,ifnull(h.subincome,'house_tax') subincome,ifnull(H.RUPEES,0) taxpaid
FROM FINANCIAL_YEARS F
LEFT JOIN house_details H ON H.HOUSE_ID = F.HOUSE_NUMBER AND H.SUBINCOME = 'house tax' and f.year = h.financial_year
#where f.house_number = 22
union all
SELECT F.`house_number`, F.`year`, F.`light_tax`, F.`createdAt`, F.`updatedAt`,ifnull(h.subincome,'light tax'),ifnull(H.RUPEES,0)
FROM FINANCIAL_YEARS F
LEFT JOIN house_details H ON H.HOUSE_ID = F.HOUSE_NUMBER AND H.SUBINCOME = 'light tax' and f.year = h.financial_year
#where f.house_number = 2
union all
SELECT F.`house_number`, F.`year`, F.`garbage_tax`, F.`createdAt`, F.`updatedAt`,ifnull(h.subincome,'garbage tax'),ifnull(H.RUPEES,0)
FROM FINANCIAL_YEARS F
LEFT JOIN house_details H ON H.HOUSE_ID = F.HOUSE_NUMBER AND H.SUBINCOME = 'garbage tax' and f.year = h.financial_year
#where f.house_number = 2
) s
join consumer_details c on s.house_number = c.house_number
where s.year <> '2017-2018'
group by c.consumer_name , s.house_number, c.address
將您的結果粘貼爲文本而不是圖像。有些人看不到圖像。 –
鏈接是圖像而不是sqlfiddle。 –
@ P.Salmon是的,我更新請檢查。 –