Microsoft SQL Server - Using Derived Tables to Calculate Aggregate Values - SQLTeam.com:
Garth on 11/18/2001 in SELECT |
Calculating aggregate values can be simplified by using derived tables. In this article I show you how to use derived tables to calculate two independent aggregate values in a single SELECT statement. |
Derived Table BasicsA derived table is one that is created on-the-fly using the SELECT statement, and referenced just like a regular table or view. Derived tables exist in memory and can only be referenced by the outer SELECT in which they are created. A simple use of a derived table is shown here. SELECT * The inner SELECT produces a derived table and replaces a regular table or view. The key thing to remember when using derived tables is that you must always use an alias (e.g., AS a). The following shows the error produced when the alias is omitted. SELECT * Referencing Multiple Derived TablesYou can add as many derived tables as needed to a single outer SELECT to produce the desired resultset. The code starts to get a little convoluted after the second inner SELECT is added, but if you focus on the columns returned by each SELECT it all makes sense. The following script creates Stores/Sales information and shows how to calculate current month and year-to-date sales count and amounts by Store. USE tempdb The first inner SELECT calculates August's sales by comparing the month and year of @RunDate to the month and year of Sal_Date. Notice that I subtracted one month from @RunDate, because the assumption is the code is executed after the previous month has closed. You should also notice that the outer SELECT uses "a1." to specify which Sto_Name is returned. The column needs to be qualified because it exists in both the a1 and b1 derived tables. The second inner SELECT calculates year-to-date totals by comparing the year of @RunDate to the year of Sal_Date. Once this table has been derived it can be joined to a1 on Sto_Name so the two independent aggregate values can be combined in the same resultset. |
0 Comments:
Post a Comment
<< Home