简体   繁体   中英

Difference between two SQL Queries

I'm writing an SQL query to select the top 50 values from a column, then calculate the average of those values. I have written two queries to accomplish this, but they are giving two different values. I believe the second one below is the correct one, but I'd like to know what the different is between the two and what the first is actually calculating (if I am in fact correct that the second is right).

First Query:

SELECT TOP(50) AVG(COL1) AS COL1_AVG FROM dbo.Table

Second Query:

SELECT AVG(COL1) FROM (SELECT TOP(50) COL1 FROM dbo.Table) AS COL1_AVG

Updated Second Query, with TimeStamp:

SELECT AVG(COL1) FROM (SELECT TOP(50) COL1 FROM dbo.Table ORDER BY TimeStamp DESC) AS COL1_AVG

The first query is averaging all rows in dbo.Table -- it's taking the TOP 50 averages, but there's only one value.

The second query is taking the top 50 rows (ordered by nothing in particular), and then averaging them. The second query is what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM