我有一张表spending
,其中包含一些基本字段,用于定义购买项目,购买时间和购买价值,以及从中购买的帐户:{{1} },spItem
,spAmount
和spDate
。
我已经提出了一个查询,每月对它们进行分组,一次一个帐户,这样可以正常工作:
spAccount
和
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)
ORDER BY YEAR(spDate), MONTH(spDate)
我正在尝试获取一个可以合并两个查询的表,并将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)
ORDER BY YEAR(spDate), MONTH(spDate)
显示在一列中,并Bank1
显示在下一列中。可能有几个月其中一个账户没有支出。在这种情况下,它应显示零值,而不是跳过它。
任何能够以正确的方式指出我的人都将非常感激。
答案 0 :(得分:0)
将年份和月份的日期选择组合为一个将相应排序和分组的字段。另外,请确保首先对帐户进行分组,因为SQL中的分组顺序很重要。
答案 1 :(得分:0)
SELECT YEAR(spDate) as spYear, MONTH(spDate) as spMonth, SUM(spAmount) AS TotalAmount,(SELECT SUM(spAmount) AS TotalAmount2 FROM spending WHERE spAccount like 'Bank2' GROUP BY YEAR(spDate), MONTH(spDate) ORDER BY YEAR(spDate), MONTH(spDate)) FROM spending WHERE spAccount like 'Bank1' GROUP BY YEAR(spDate), MONTH(spDate) ORDER BY YEAR(spDate), MONTH(spDate)
答案 2 :(得分:0)
我希望我能正确理解你的问题: - )
对于每个可用的月份和年份(其中至少有一个帐户中存在数据)显示每个帐户的SUM(即使其中一个帐户为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
答案 3 :(得分:0)
您可以使用条件聚合分组在一个查询中获取两个帐户的总计。这就是它的样子:
SELECT YEAR(spDate) as spYear,
MONTH(spDate) as spMonth,
SUM(CASE spAccount WHEN 'Bank1' THEN spAmount ELSE 0 END) AS Bank1,
SUM(CASE spAccount WHEN 'Bank2' THEN spAmount ELSE 0 END) AS Bank2
FROM spending
WHERE spAccount IN ('Bank1', 'Bank2')
GROUP BY YEAR(spDate), MONTH(spDate)
ORDER BY YEAR(spDate), MONTH(spDate)
;