home
training courses
why choose us?
solutions
support
company
LearnItFirst User Forum
Welcome Guest
Search
|
New Posts
|
Members
|
Log In
|
Register
SQL Server Forum - LearnItFirst.com
»
SQL Server Scripts, Code Samples and SSMS Custom Reports
»
All SQL Server Versions
»
How to Rewrite a Derived Table to Use a Table Variable
How to Rewrite a Derived Table to Use a Table Variable
Options
Previous Topic
·
Next Topic
Scott Whigham
Posted:
Tuesday, November 07, 2006 11:36:00 AM
Rank: Super Mod
Joined: 3/20/2006
Posts: 476
Points: 1,053
Where do you live?: 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: Take derived table and create table variable from definition:
DECLARE @MyTable TABLE (OrderId INT, TotalSales MONEY)
-- Step 2: Populate the table variable with the derived table's result set
INSERT @MyTable
SELECT OrderId, SUM(NetAmount) AS TotalSales
FROM [Order Details]
GROUP BY orderId
-- Step 3: Replace derived table in original query with table variable
SELECT Avg(TotalSales)
FROM @MyTable
This is a tricky one. You must run all of this as one statement since the scope of the variable is the batch.
Back to top
Users browsing this topic
Guest
Forum Jump
SQL Server Database Administration
- General SQL Database Question & Answer
- Backup, Recovery and Disaster Recovery
- SQL Server Security
- Integration Services (SSIS) and DTS
Transact-SQL Programming
- DML (SELECT, INSERT, UPDATE, DELETE) Questions
- Stored Procedures, Triggers, & Functions
SQL Server Scripts, Code Samples and SSMS Custom Reports
- All SQL Server Versions
- SQL Server 2005/2008
- SQL Server Management Studio Custom Reports
Customer Service
- Video Requests
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.
SQL Server 2005 DBA Training Videos
SQL Server 2008 DBA Training Videos
Email this topic
RSS Feed
Watch this topic
Print this topic
Normal
Threaded