3

我需要一个查询,总计费用实际年初至今,平均年初至今(在所有年份中,我的平均年份是多少),去年年初至今

我需要 3 条数据:实际 YTD | 年初至今平均 | 过去几年|

这是我到目前为止所拥有的:

select  SUM(Expenses)
        ,DATEADD(year, datediff(year,0,[Date]), 0) 
from    table1 
group by  
        DATEADD(year, datediff(year,0,[Date]), 0) 
) 
4

2 回答 2

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

SQL小提琴

于 2012-09-07T12:19:20.207 回答
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
于 2012-09-07T12:13:16.890 回答