Member of the LearnItFirst.com Video Training Network | LearnSqlServer.com | SQL SSIS Training | SQL Programming Tutorials |
LearnSqlServer.com Forums LearnSqlServer.com
Welcome Guest Search | New Posts | Members | Log In | Register

How to Rewrite a Derived Table to Use a Temporary Table Options
Scott Whigham
Posted: Tuesday, November 07, 2006 11:33:39 AM


Rank: Super Mod

Joined: 3/20/2006
Posts: 345
Points: 748
Location: Dallas, TX
I put this up because, in one class I teach, we talk about how to rewrite a derived table to use a view.
Code:
-- What is the average sales price?
--            This must be done in two steps because you cannot take an aggregate of an aggregate
--            This is based on the Northwind database
SELECT Avg(TotalSales)
FROM (
    SELECT OrderId, SUM(NetAmount) AS TotalSales
    FROM [Order Details]
    GROUP BY orderId
) AS x

-- Step 1: Use SELECT INTO to create table (take derived table query and make a table based on it)
SELECT OrderId, SUM(NetAmount) AS TotalSales
    INTO ScottsNewTable
    FROM [Order Details]
    GROUP BY orderId

-- Step 2: rewrite the query to refer to the new table
SELECT Avg(TotalSales)
FROM ScottsNewTable
Hope this helps Smile
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.
     
Don't Forget!
LearnItFirst.com
Don't Forget!
LearnSqlServe.com
 
Home | About Us | Support | Contact Us | Privacy | Site Map | Blogs Blogs Refer a Friend and Get a Free Subscription!
© Copyright 2004-2007 LearnItFirst.com LLC. All rights reserved. All trademarks remain the property of their respective owners.
This site is not affiliated in any way with the Microsoft Corporation.