2016-08-31 3 views
1

Ich habe eine Tabelle mit Spalten ID, Title, Date, Amount.SQL-Abfrage für die Berechnung mtd, YTD Werte

Ich muss MTD, YTD Betrag Werte für jede Transaktion basierend auf Title, Date erhalten.

Gibt es jemanden, der das schon mal gemacht hat?

+2

Bitte bearbeiten Sie zunächst prüfen diese Frage: http://stackoverflow.com/help/formatting – neohope

Antwort

2
Select t.title, t.Date, 
    Sum(y.Amount) YTD, 
    Sum(m.Amount) MTD 
From table t 
    join table y 
     on y.Title = t.Title 
     and datediff(year, y.Date, t.Date) = 0 
     and y.Date <= t.Date 
    join table m 
     on m.Title = t.Title 
     and datediff(month, m.Date, t.Date) = 0 
     and m.Date <= t.Date 
Group by t.title, t.Date 
+0

Dank! Wirklich hilfreich –

1
SELECT ID, 
     Title, 
     Date, 
     Amount, 
     MTD = SUM(Amount) OVER (PARTITION BY Title, DATEADD(MONTH, DATEDIFF(MONTH, 0, [Date]), 0)), 
     YTD = SUM(Amount) OVER (PARTITION BY Title, DATEADD(YEAR, DATEDIFF(YEAR, 0, [Date]), 0)) 
FROM [a_table] 
+0

Danke! Wirklich hilfreich –