INF: How to Write a Variance Query in SQL Server

Last reviewed: January 8, 1998
Article ID: Q175955
The information in this article applies to:
  • Microsoft SQL Server versions 6.0 and 6.5

When you need to make a comparison between a value and the average for that value in the same category, you can execute a variance query. For example, you may want to use a variance query when you want to compare the salary of an employee against the salary of other employees who hold the same title, or when you want a comparison between the price of a book and the price of all the other books of the same category.

To continue the book example, you can execute the query below in the pubs database. Note that this is a correlated subquery, so it will take a while to run against a very large table.

   select
      title,
      price,
      variance = price - (select avg(price)
                                    from titles t2
                                    where t2.type = t1.type)
   from titles t1


Additional query words: sub variant
Keywords : SSrvGen kbusage
Version : WINNT:6.0 6.5
Platform : winnt
Issue type : kbhowto
Solution Type : Info_Provided


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: January 8, 1998
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.