如果值大于平均值,mysql将显示数据

t5fffqht  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(345)

我有这个查询,我想选择或显示作者的图书数量高于平均水平。
到目前为止,我得到的平均图书数量查询如下:

SELECT AVG(c.quantity) AS 'Average'
FROM(
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al
GROUP BY al.autores_DNI
) AS c

我怎样才能只挑选(显示)那些书的数量高于平均水平的作者呢?
此查询列出作者及其图书数量:

SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
    FROM autores_has_libros AS al
    GROUP BY al.autores_DNI

我试过:

SELECT a.first_name 
FROM autores AS a
HAVING (
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
    FROM autores_has_libros AS al
    GROUP BY al.autores_DNI
)
> (
SELECT AVG(c.quantity) AS 'Average'
    FROM(
    SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
    FROM autores_has_libros AS al
    GROUP BY al.autores_DNI
    ) AS c
)

但这行不通

nmpmafwu

nmpmafwu1#

如果要使用一条sql语句获得结果,可以尝试以下sql:

SELECT a.first_name FROM autores AS a 
RIGHT JOIN 
(
    SELECT autores_DNI AS Author, COUNT(*) AS quantity
    FROM autores_has_libros WHERE quantity > (
        SELECT AVG(quantity) AS Average FROM
        (
            SELECT autores_DNI AS Author, COUNT(*) AS quantity
            FROM autores_has_libros
            GROUP BY autores_DNI
        )
    )
    GROUP BY autores_DNI
) b ON a.author = b.Author

但是,我建议您可以使用语言代码在比较之前获得平均值,或者使用mysql程序。

lhcgjxsq

lhcgjxsq2#

您可以尝试将平均值保存在变量中,然后使用以下选项进行选择:

Set @avg = SELECT AVG(c.quantity) AS 'Average'
FROM(
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al
GROUP BY al.autores_DNI
) AS c

SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al where COUNT(*) >= @avg

我不确定这是否行得通,但你可以想出一个办法。

3mpgtkmj

3mpgtkmj3#

中的第一个子查询 HAVING 子句不仅仅返回当前作者的计数,它还返回所有其他作者的计数。但是 SELECT 用作值只能返回一个值。
相反,应该与子查询联接。

SELECT a.first_name
FROM aotores AS a
JOIN (
    SELECT al.autores_DNI AS Author,COUNT(*) AS quantity
    FROM autores_has_libros AS al
    GROUP BY Author) AS al ON al.Author = a.DNI
JOIN (
    SELECT AVG(c.quantity) AS Average
    FROM (
        SELECT COUNT(*) AS quantity
        FROM autores_has_libros AS al
        GROUP BY al.autores_DNI) AS c
) AS av ON al.quantity > av.Average

顺便说一句,在mysql中,标识符是用反引号引用的,而不是单引号。单引号用于创建文字字符串。

相关问题