3

経費を合計するクエリが必要です 実際のYTD、平均YTD(すべての年のうち、私の平均年は何ですか)、昨年のYTD

3 つのデータが必要です: 実際の YTD | 実際の 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 に答える