![]() | |
#1
| |||
| |||
|
#2
| |||
| |||
|
#3
| |||
| |||
|
|
This should give you a good start to solve the problem. The idea is to calculate the totals per week, then create rank based on weeks and pull the first 13 ranks (since rank is in descending order you get the latest 13 weeks), and finally pivot on the rank. WITH Totals AS ( SELECT doc, * * * * SUM(totovr) / NULLIF(SUM(totpnd), 0) AS total, * * * * weekdat FROM PendingdiarySDW GROUP BY doc, weekdat), Ranked AS ( SELECT doc, total, DENSE_RANK() OVER(ORDER BY weekdat DESC) AS rk FROM Totals) SELECT doc, [1], [2], [3], [4], [5], [6], * * * * [7], [8], [9], [10], [11], [12], [13] FROM Ranked PIVOT (SUM(total) FOR rk IN ([1], [2], [3], [4], [5], [6], * * * * * * * * * * * * [7], [8], [9], [10], [11], * * * * * * * * * * * * [12], [13])) AS P; -- Plamen Ratchevhttp://www.SQLStudio.com |
#4
| |||
| |||
|
#5
| |||
| |||
|
|
You have to use dynamic SQL to generate the column names based on the last 13 dates. The following article will give you an idea on how to implement that:http://pratchev.blogspot.com/2008/12...-pivoting.html But normally this type of column header formatting should be done client side. -- Plamen Ratchevhttp://www.SQLStudio.com |
#6
| |||
| |||
|
|
On Nov 10, 1:31*pm, Plamen Ratchev <Pla... (AT) SQLStudio (DOT) com> wrote: You have to use dynamic SQL to generate the column names based on the last 13 dates. The following article will give you an idea on how to implement that:http://pratchev.blogspot.com/2008/12...-pivoting.html But normally this type of column header formatting should be done client side. -- Plamen Ratchevhttp://www.SQLStudio.com Okay thanks going to read the article now. |
#7
| |||
| |||
|
#8
| |||
| |||
|
|
SQL Server cannot evaluate the variable value in the SELECT list. You have to use dynamic SQL (like in the article that I posted) to concatenate the SQL to the variable with columns (in two places, in the SELECT and in the PIVOT clauses). -- Plamen Ratchevhttp://www.SQLStudio.com |
#9
| |||
| |||
|
#10
| |||
| |||
|
|
You did not make the query dynamic. Also, the query has errors (you define CTEs, calculate expressions, and never use the CTEs, plus last query is incorrect). DECLARE @sql NVARCHAR(2000); SET @sql = N' WITH Totals AS ( SELECT doc, CASE * WHEN SUM(totovrSDW) + SUM(totovr) = 0 THEN 0 * WHEN SUM(totpndSDW) + SUM(totpnd) = 0 THEN 0 * ELSE (convert(decimal(6,1),(((((sum(totovrSDW) + sum(totovr))) * 1.00) */ (sum(totpndSDW) + sum(totpnd))) * 100))) * END AS total, weekdat FROM PendingdiarySDW GROUP BY doc, weekdat) SELECT doc,' + @listCols + N' FROM * *(SELECT doc, total, weekdat * * FROM Totals) as O ' + * * * * *N' PIVOT ' + N'(SUM(total) FOR weekdat IN (' + @listCols + N')) AS P;'; EXEC(@sql); -- Plamen Ratchevhttp://www.SQLStudio.com |
![]() |
| Thread Tools | |
| Display Modes | |
| |