我需要计算每周5年的现金流量。
源表:
ID WeekNumber DayTime Dollars
1 1 2012-01-01 10
2 1 2012-01-02 10
3 2 2012-01-08 20
....
353 1 2013-01-01 30
表格包含每天5年的天数。 WeekNumber从每年的数字1开始。
总之,视图应该如下:
WeekNumber CashFlow
1 (sum)
2 (sum)
3 (sum)
....
1 (sum)
2 (sum)
3 (sum)
我试过了:
SELECT *,
CashFlow = (SELECT SUM(X.TotalSum) as TT
FROM (SELECT WeekNumber, SUM(Dollars) as TotalSum
FROM dbo.Temp
GROUP BY WeekNumber) X
WHERE X.WeekNumber <= Y.WeekNumber)
FROM(SELECT WeekNumber, SUM(Dollars) as TotalSum
FROM dbo.Temp
GROUP BY WeekNumber) Y
ORDER BY WeekNumber ASC
一年它会返回正确的数字,但是5年后它只返回53行,包含每年每周的现金流量总和。
您有什么想法如何改善它以获得所需的结果?
答案 0 :(得分:1)
您需要使用Year列来分割每年的总计,您可以使用Year函数中包含的DateTime列来动态执行此操作
SELECT
WeekNumber, Year = YEAR(DayTime), CashFlow = SUM(Dollars)
From InsertFromExel.dbo.Temp
Group By
WeekNumber, YEAR(DayTime)
答案 1 :(得分:0)
这适用于您描述的表以及您想要的输出: (编辑:如果您希望您的确切输出从SELECT中删除年份部分)
SELECT YEAR(DayTime) as Year, WeekNumber, SUM(Dollars) as CashFlow
FROM InsertFromExel.dbo.Temp
GROUP BY WeekNumber, YEAR(DayTime)
ORDER BY Year asc, WeekNumber asc
按年份分组(DayTime)和WeekNumber将合并这两个属性匹配的所有行并生成单个结果行。通过SUM(美元),为每个匹配添加所有美元,并将总和作为相应结果行的输出。 ORDER BY按年排序,然后按周排序(asc =升序)。
编辑:添加ORDER BY部分。
答案 2 :(得分:0)
这是有用的
create table #tmp (ID Int, weeknumber int, DayTime DATETIME,Dollars int)
insert into #tmp values(1,1,'2012-01-01',10)
insert into #tmp values(1,1,'2012-01-02',10)
insert into #tmp values(1,2,'2012-01-08',20)
insert into #tmp values(1,2,'2012-01-09',30)
insert into #tmp values(1,3,'2012-01-15',90)
insert into #tmp values(1,3,'2012-01-16',30)
insert into #tmp values(1,1,'2013-01-01',30)
insert into #tmp values(1,1,'2013-01-02',10)
insert into #tmp values(1,2,'2013-01-08',40)
insert into #tmp values(1,2,'2013-01-09',20)
insert into #tmp values(1,3,'2013-01-15',60)
insert into #tmp values(1,3,'2013-01-16',70)
select weeknumber,Sum(Dollars) As Cashflow from #tmp
Group by Year(DayTime),weeknumber
order by Year(DayTime),weeknumber
drop table #tmp