[英]Add a row total to a view
new to SQL and I'm looking to do some work with income per month and quarterly/annual totals. SQL的新手,我希望做一些月收入和季度/年度总计的工作。
I have a mock view which pulls information from a company table (giving us company ID and CompanyName) and an income table (giving us the remaining 4 columns) like this: 我有一个模拟视图,它从公司表(给我们公司ID和CompanyName)和收入表(给我们剩下的4列)中提取信息,如下所示:
CompanyID |CompanyName |IncomeType |Jan |Feb |Mar
-----------------------------------------------------------
1 |Big Stuff |Cars |1000 |200 |500
2 |Huge Stuff |Lorries |2000 |4000 |5000
What I'd like is to be able to sum Jan+Feb+Mar as a Total
column per CompanyID
. 我想要的是能够将Jan + Feb + Mar作为每个
CompanyID
的Total
列求和。
I'm having problems with including the sum(J+F+M) as first SQL asks for a group on the companyID
, then once that's grouped, it asks for grouping on CompanyName
and so on. 我在包含sum(J + F + M)时遇到问题,因为第一个SQL要求在
companyID
上进行分组,然后对它进行分组,然后再对CompanyName
进行分组,依此类推。
Any help gratefully received. 非常感谢任何帮助。
Maybe this... 也许这个...
SELECT C.companyID, C.CompanyName, C.IncomeType, sum(Jan) J , sum(Feb) F,
sum(Mar) M, sum(Jan+Feb+Mar) as Total
FROM company C
INNER JOIN Income I
on C.CompanyID = I.CompanyId
GROUP BY C.companyID, C.CompanyName, C.IncomeType
You don't need the sum()
, unless you have an aggregation query already. 除非已经有聚合查询,否则不需要
sum()
。 So, something like: 因此,类似:
select c.companyID, c.CompanyName, i.IncomeType, i.Jan, i.Feb, i.Mar,
(i.Ja + i.Feb + i.Mar) as Total
from company c join
income i
on c.companyid = i.companyid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.