I know how views are used, but I still don't see the real benefits of using them.
For example, in the following article http://techahead.wordpress.com/2007/10/01/sql-derived-tables/, the author tried to show the benefits of a query using a query view without one with an example where we want to create a report that shows the total number of orders, each customer placed in 1996, and we want this result set to include all customers, including those who did not place any orders this year, and those who never placed any orders at all ( HPP using the Northwind database).
But when I compare two queries, I donβt see any advantages of the query using the view (if nothing else, using the view does not simplify our code, at least not in this example)
Normal query:
SELECT C.CustomerID, C.CompanyName, COUNT(O.OrderID) AS TotalOrders FROM Customers C LEFT OUTER JOIN Orders O ON C.CustomerID = O.CustomerID AND YEAR(O.OrderDate) = 1996 GROUP BY C.CustomerID, C.CompanyName
Query using a view:
SELECT C.CustomerID, C.CompanyName, COUNT(dOrders.OrderID) AS TotalOrders FROM Customers C LEFT OUTER JOIN (SELECT * FROM Orders WHERE YEAR(Orders.OrderDate) = 1996) AS dOrders ON C.CustomerID = dOrders.CustomerID GROUP BY C.CustomerID, C.CompanyName
Perhaps this just was not a good example, so could you show me an example where the benefits of a view are more obvious?
thanks
ANSWER TO HEAD:
In this case, you cannot capture both products and order aggregates if there is no connection between the Customers and the Products.
Could you clarify what exactly you mean? Will the following query return the same result as your query:
SELECT C.CustomerID, C.CompanyName, COUNT(O.OrderID) AS TotalOrders, COUNT(DISTINCT P.ProductID) AS DifferentProducts FROM Customers C LEFT OUTER JOIN Orders O ON C.CustomerID = O.CustomerID AND YEAR(O.OrderDate) = 1996 LEFT OUTER JOIN Products P ON O.somethingID = P.somethingID GROUP BY C.CustomerID, C.CompanyName
RESPONSE TO ROUX FRAME:
In addition, if expressions are used to derive columns from derived columns with a lot of intermediate calculations, a set of nested views or stacked CTEs is the only way to do this:
SELECT x, y, z1, z2 FROM ( SELECT * ,x + y AS z1 ,x - y AS z2 FROM ( SELECT x * 2 AS y FROM A ) AS A ) AS A
Will the following query return the same result as the above query:
SELECT x, x * 2 AS y, x + x*2 AS z1, x - x*2 AS z2 FROM A