I have a SQL query and it's creating a PIVOT table.
Here is it.
SELECT *
FROM (
SELECT
Name
,Year
,sum(Payment) as TotalPayment
FROM Orders
group by Name,Date
) as Tablo
PIVOT
(
SUM(TotalPayment)
FOR Date IN ([2009-11],[2009-12],[2010-01])
)
AS p
It's getting monthly total payment and the guy who wrote this query adding year-month manually every month. I need to do it dynamically.
How can I get month-year dynamically from table using SQL query with loop or something like that ?
Thanks for your helps !
Dynamic SQLDATEADD(MONTH,-2,GETDATE())group by Name, datediff(month,Date,getdate() as r_month )...FOR r_month IN ([-1], [-2], ... )Remember to limit the number of months onwhereclause.