我需要一个查询,总计支出实际年初至今,平均年初至今(所有年份,我的平均年份),去年年初
我需要3个数据:实际YTD |平均年初至今|去年|
这是我到目前为止所做的:
select SUM(Expenses)
,DATEADD(year, datediff(year,0,[Date]), 0)
from table1
group by
DATEADD(year, datediff(year,0,[Date]), 0)
)
答案 0 :(得分:2)
试试这个:
DECLARE @currentYear int
SELECT @currentYear = DATEPART(year, GETDATE())
SELECT SUM(CASE WHEN DATEPART(year,[date]) = @currentYear
THEN Expenses ELSE 0 END) AS 'Actual YTD',
SUM(Expenses) / COUNT( DISTINCT DATEPART(year,[date])) AS 'Average YTD',
SUM(CASE WHEN DATEPART(year,[date]) = @currentYear -1
THEN Expenses ELSE 0 END) AS 'Last Year YTD'
FROM Table1
答案 1 :(得分:1)
试试这个
select
AVG(case when
[date]>=DATEADD(year, datediff(year,0,getDate())-1, 0) and
[date]<DATEADD(year, datediff(year,0,getDate()), 0)
then Expenses end)
as average_ytd,
sum(case when
[date]>=DATEADD(year, datediff(year,0,getDate())-1, 0) and
[date]<DATEADD(year, datediff(year,0,getDate()), 0)
then Expenses else 0 end)
as actual_ytd,
sum(case when
[date]>=DATEADD(year, datediff(year,0,getDate())-2, 0) and
[date]<DATEADD(year, datediff(year,0,getDate())-1, 0)
then Expenses else 0 end)
as lat_year_ytd
from
table1