INF: How to Write a Variance Query in SQL Server
Article ID: 175955
Article Last Modified on 3/14/2005
APPLIES TO
- Microsoft SQL Server 6.0 Standard Edition
- Microsoft SQL Server 6.5 Standard Edition
- Microsoft SQL Server 7.0 Standard Edition
- Microsoft SQL Server 2000 Standard Edition
This article was previously published under Q175955
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: kbhowto kbusage KB175955