Pivoting is a tougher one to understand because the syntax seems to be more challenging then simply, select, from, join, where stuff… Tangent real quick --> I started writing my home work code in the grouping lessons starting with FROM, then going back and writing SELECT after, I believe logically that is how SQL works, and it definitely makes sense… try it it works great!
Back to pivoting, yes hard to understand because the syntax is different, but as long as you know what it does and what goes where I think it can be useful. I've read a few blogs on pivoting because the book only got me so far, and stumbled upon a few very good articles, as well as comments. Here was one in which help turn on the light for me because of the fact that they make a practical use out of pivoting, in an explanation of WHY you might use it. I'm going to copy and paste now from this website/blog: http://terrychoo.com/understanding-the-pivot-function/
Terry gives the example of creating a table:
-- CREATE TABLE AND FILL WITH SAMPLE DATA
DECLARE @orders TABLE
(
custid INT,
empid INT,
shipperid INT,
freight NUMERIC(10,2)
)
(
custid INT,
empid INT,
shipperid INT,
freight NUMERIC(10,2)
)
INSERT INTO @orders (custid, empid, shipperid, freight)
VALUES (85,5,3,32.38),
(85,6,1,6.01),
(85,2,2,1.15),
(85,2,2,7.79),
(85,3,3,11.08);
VALUES (85,5,3,32.38),
(85,6,1,6.01),
(85,2,2,1.15),
(85,2,2,7.79),
(85,3,3,11.08);
A practical use for this data comes by way of a comment at the bottom of the page by "ronin" who writes, "Perhaps you could mention the motivation for pivoting before you explain it. You could say – find me the total freight for each shipper id associated with each customer id like this custid, shipperId1, shipperId2, shipperId3 etc. If you don’t mention the second part, then the reader might wonder why you are using pivoting. They might wonder if could just use a group by instead-"
The light went on as I read that and thought to myself… bingo! Homework question for myself! I don't think that I need to get in depth with pivoting but I should be able to figure a simple problem like that out given the data. The correct answer for this query is in the blog, but I will definitely put it in my homework set and try not to peek. This will help my understanding of how to PIVOT the data, UNPIVOTING will be next, something that I hope to understand deeper once I have the PIVOT piece down first.
Cheers!
No comments:
Post a Comment