20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Advanced Queries<br />

What you really want, however, is to group the orders according to the month and year in which they<br />

were placed, necessitating a GROUP BY clause:<br />

SELECT FirstName, LastName,MONTH(OrderDate)AS Month, YEAR(OrderDate) As Year<br />

FROM Orders INNER JOIN SalesPerson<br />

ON Orders.SalesPersonId = SalesPerson.SalesPersonId<br />

GROUP BY FirstName,LastName,MONTH(OrderDate), YEAR(OrderDate);<br />

Executing the preceding query groups the results by salesperson, month, and year, as shown in the following<br />

table:<br />

FirstName LastName Month Year<br />

Daphne Moon 1 2007<br />

Daphne Moon 11 2006<br />

Daphne Moon 12 2006<br />

Frasier Crane 10 2006<br />

Frasier Crane 11 2006<br />

Frasier Crane 12 2006<br />

Sandra Hugson 1 2007<br />

Sandra Hugson 7 2006<br />

Sandra Hugson 8 2006<br />

Sandra Hugson 9 2006<br />

Sandra Hugson 10 2006<br />

Sandra Hugson 11 2006<br />

Sandra Hugson 12 2006<br />

So far, you have a list of salespeople as well as month and year values. There’s no link to the items contained<br />

in each order. Your next task is to link the current tables, SalesPerson and Orders, to items in each<br />

order. This data is contained in the OrderItems table, which is the next table to which you must create a<br />

link. The value that links the current tables and OrderItems is the OrderId present in the Orders and<br />

OrderItems tables. Join OrderItems to the current tables using an inner join, as illustrated in the following<br />

statement:<br />

SELECT FirstName, LastName,MONTH(OrderDate)AS Month, YEAR(OrderDate) AS Year<br />

FROM (Orders INNER JOIN SalesPerson ON Orders.SalesPersonId =<br />

SalesPerson.SalesPersonId)<br />

INNER JOIN OrderItems ON OrderItems.OrderId = Orders.OrderId<br />

GROUP BY FirstName,LastName,MONTH(OrderDate), YEAR(OrderDate);<br />

If you run this query, you won’t see any difference between these results and the previous results. Also,<br />

what you’re really after is the total cost of all orders placed in each month by each salesperson, which is<br />

represented by the SUM(DVDPrice) data in the original SELECT list described previously. However, the<br />

273

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!