How to compare the values of a column with the average of these values in SQL?

Asked

Viewed 637 times

2

I have a column of books, and I just want to show the books that the price is higher than the average of those prices, how to do that? The name of my column is price, and I can’t put a where price > avg(price), neither a having price > avg(price).

1 answer

1


You can calculate the average before and assign to a variable:

DECLARE @media numeric(15, 2);

SELECT @media = AVG(l.price)
  FROM livros l;

SELECT l.*
  FROM livros l
 WHERE l.price > @media;

Or perform a CROSS JOIN with the calculated value:

SELECT l.*
  FROM livros l
       CROSS JOIN (SELECT AVG(l2.price) AS media
                     FROM livros l2) m
 WHERE l.price > m.media;

A third way is to calculate the average with the WITH:

WITH media AS (
  SELECT AVG(l2.price) AS media
    FROM livros l2
)
SELECT l.*
  FROM livros l
 WHERE l.price > (SELECT m.media
                    FROM media m);
  • What is the meaning of this (15,2)?

  • 1

    @M.Amaral the 15 is the size of the whole part of the number and the 2 is the maximum of decimal places that will be stored

  • The person responsible for downvote can explain why the answer would be wrong? I don’t understand the downvote without explanation and reason.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.