INF: How to Write a Variance Query in SQL Server

ID: Q175955


The information in this article applies to:
  • Microsoft SQL Server versions 6.0, 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 : kbusage SSrvGen
Version : winnt:6.0,6.5
Platform : winnt
Issue type : kbhowto


Last Reviewed: August 11, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.