Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
How to do inside quotes
Message
 
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Environment versions
SQL Server:
SQL Server 6.5 and older
Application:
Web
Miscellaneous
Thread ID:
01582787
Message ID:
01582807
Views:
43
>Also...and I can't say for certain, but I think the final query at the end 'might' need to quality the values of the spreading element.
>
>Since you mentioned you were starting out wit PIVOT, here is an example (that doesn't use dynamic sql), that uses the AdventureWorks database
>
>
>;with ordercte as ( select ShipMethodID, 
>              datepart(q,orderdate) as qnum, TotalDue from purchasing.PurchaseOrderHeader )
>
>select ShipMethodID, [1] as Q1, [2] as Q2, [3] as Q3, [4] as Q4 from ordercte
>   pivot ( sum(TotalDue) for Qnum in ( [1], [2], [3], [4]) )  PivotResult
>order by ShipMethodID
>
>Note that the values for the spreading element of QNum (Quarter number) are across the top.
>
>I might be off-base here, but you might want to make sure you have a static query to serve as a model for what the dynamic query should look like. To this day, any time I have to use dynamic sql (especially with pivot), I wind up writing a static query first, to make sure I've got everything accounted for. And then once I do, I'll implement it as a dynamic query. That way, if I run into problems, I can at least compare my generated syntax against what I know was a correct query to begin with.
>
>Hope that helps...

Exactly what I do as well. BTW, I have two articles in TechNet on PIVOT theme - they both won the gold prize in the TechNet Guru Contribution for May:

http://social.technet.microsoft.com/wiki/contents/articles/17510.t-sql-dynamic-pivot-on-multiple-columns.aspx

and

http://social.technet.microsoft.com/wiki/contents/articles/17351.sql-server-pivot.aspx
If it's not broken, fix it until it is.


My Blog
Previous
Reply
Map
View

Click here to load this message in the networking platform