Home Forums SQL Server 2005 T-SQL (SS2K5) Query that Returns Month to Date and YTD in Same Record RE: Query that Returns Month to Date and YTD in Same Record

  • You'll need to run them separately, then combine them in a final query.

    Perhaps something like:

    ;with

    Daily (DAcctCode, TotalDailyRevenue, DDay, DMonth, DYear) as

    (select AcctCode,

    isnull(sum(FuelFee), 0)

    + isnull(sum(CashFee), 0)

    + isnull(sum(ScFee), 0),

    datepart(day, TxnDate),

    datepart(month, TxnDate)

    datepart(year, TxnDate)

    from TxnRptg.dbo.tbl_DailySummary

    group by AcctCode,

    datepart(day, TxnDate),

    datepart(month, TxnDate)

    datepart(year, TxnDate)),

    Monthly (MAcctCode, TotalMonthlyRevenue, MMonth, MYear) as

    (select AcctCode,

    isnull(sum(FuelFee), 0)

    + isnull(sum(CashFee), 0)

    + isnull(sum(ScFee), 0),

    datepart(month, TxnDate)

    datepart(year, TxnDate)

    from TxnRptg.dbo.tbl_DailySummary

    group by AcctCode,

    datepart(month, TxnDate)

    datepart(year, TxnDate)),

    Yearly (YAcctCode, TotalYearlyRevenue, YYear) as

    (select AcctCode,

    isnull(sum(FuelFee), 0)

    + isnull(sum(CashFee), 0)

    + isnull(sum(ScFee), 0),

    datepart(year, TxnDate)

    from TxnRptg.dbo.tbl_DailySummary

    group by AcctCode,

    datepart(year, TxnDate))

    select DAcctCode as AcctCode, TotalDailyRevenue, TotalMonthlyRevenue,

    TotalYearlyRevenue

    from Daily

    inner join Monthly

    on DAcctCode = MAcctCode

    and DMonth = MMonth

    and DYear = MYear

    inner join Yearly

    on DAcctCode = YAcctCode

    and MYear = YYear

    and DYear = YYear

    Add in other tables for other columns to the Join clause.

    Does that give you what you need? It'll take at least three table scans, but it shouldn't be too bad on performance.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon