我希望我正确理解了你的问题:-)
对于每个可用的月份和年份(数据存在于至少一个帐户中)显示每个帐户的总和(即使其中一个为 0)。为此,我加入了 2 个查询并使用 ISNULL 函数从正确的源获取数据。
这是我使用虚拟数据的解决方案:
--Preparing Dummy Data
;WITH spending
AS (SELECT '01-01-2010' spDate,
100 spamount,
'Bank1' spaccount
UNION
SELECT '01-01-2010' spDate,
200 spamount,
'Bank1' spaccount
UNION
SELECT '03-01-2010' spDate,
150 spamount,
'Bank1' spaccount
UNION
SELECT '04-01-2010' spDate,
500 spamount,
'Bank1' spaccount
UNION
SELECT '01-01-2010' spDate,
200 spamount,
'Bank1' spaccount
UNION
SELECT '03-01-2010' spDate,
10 spamount,
'Bank2' spaccount
UNION
SELECT '05-01-2010' spDate,
800 spamount,
'Bank2' spaccount
UNION
SELECT '03-01-2010' spDate,
110 spamount,
'Bank2' spaccount
UNION
SELECT '01-01-2010' spDate,
100 spamount,
'Bank2' spaccount)
--End of Dummy Data
--Start Query on Dummy Data
SELECT ISNULL(Bank1.SPMONTH, Bank2.SPMONTH) AS spMonth,
ISNULL(Bank1.SPYEAR, Bank2.SPYEAR) AS spYear,
ISNULL(Bank1.TOTALAMOUNT, 0) AS TotalAmount_Bank1,
ISNULL(Bank2.TOTALAMOUNT, 0) AS TotalAmount_Bank2
FROM (SELECT YEAR(SPDATE) AS spYear,
MONTH(SPDATE) AS spMonth,
SUM(SPAMOUNT) AS TotalAmount
FROM spending
WHERE SPACCOUNT LIKE 'Bank1'
GROUP BY YEAR(SPDATE),
MONTH(SPDATE)) AS Bank1
FULL JOIN (SELECT YEAR(SPDATE) AS spYear,
MONTH(SPDATE) AS spMonth,
SUM(SPAMOUNT) AS TotalAmount
FROM spending
WHERE SPACCOUNT LIKE 'Bank2'
GROUP BY YEAR(SPDATE),
MONTH(SPDATE)) AS Bank2
ON Bank1.SPMONTH = Bank2.SPMONTH
AND Bank2.SPYEAR = Bank2.SPYEAR
ORDER BY SPYEAR,
SPMONTH