如何从子查询的SUM中过滤结果?

问题描述 投票:0回答:1

我试图从两个表的两列中返回一个计数的总和。我需要它返回大于16的结果。使用MSSQL。

我期望。

--------------------------------------
total_customers  |   album_title
-----------------|--------------------
17               |    "Blah Blah"
--------------------------------------

在没有HAVING子句的情况下,查询会按照我的预期将列数相加。

--------------------------------------
total_customers  |   album_title
-----------------|--------------------
17               |    "Blah Blah"
--------------------------------------
5                |   "another title"
--------------------------------------
3                |   "I'm a title"
--------------------------------------

当我尝试使用Greater Than (>)符号添加HAVING子句时,它不会返回任何结果。

--------------------------------------
total_customers  |   album_title
-------------------------------------

当我把它切换到Less Than(<)时,它返回所有结果。

--------------------------------------
total_customers  |   album_title
-----------------|--------------------
17               |    "Blah Blah"
--------------------------------------
5                |   "another title"
--------------------------------------
3                |   "I'm a title"
--------------------------------------

我的代码。

SELECT SUM(total_customers) as total_customers, album_title
FROM (SELECT COUNT(DISTINCT customer.id) as total_customers , album.album_title
FROM album
INNER JOIN customer ON album.album_id = customer.album_id
GROUP BY customer.id, album_title
) s
GROUP BY total_customers, album_title
HAVING total_customers > 16;
sql sql-server join subquery
1个回答
1
投票

你应该使用聚合函数与 having 如下。原因是 having 子句将先执行,然后再执行 select 而后 group by.

我已经删除了 total_customersgroup by.

SELECT 
    SUM(total_customers) as total_customers, 
    album_title
FROM 
(
    SELECT 
        COUNT(DISTINCT c.id) as total_customers , 
        a.album_title
    FROM album a
    INNER JOIN customer c
    ON a.album_id = c.album_id
    GROUP BY c.id, album_title
) s
GROUP BY 
    album_title
HAVING SUM(total_customers) > 16;
© www.soinside.com 2019 - 2024. All rights reserved.