带有having子句的SQL查询返回意外结果

发布于 2025-01-18 10:28:12 字数 1158 浏览 0 评论 0原文

我正在与Chinook数据库合作,想编写一个查询,以返回美国销售最多的流派。我的想法使用有子句和返回表格的表。

我已经写了一些不使用子句的东西,但是我想理解为什么我的子句不起作用。 :)

Here's my SQL query:

        select g.name, count(il.invoice_line_id) tracks_sold from genre g 
          inner join track t 
          on t.genre_id = g.genre_id
          inner join invoice_line il
          on il.track_id = t.track_id
          inner join invoice i
          on i.invoice_id = il.invoice_id
          inner join customer c
          on c.customer_id = i.customer_id
          group by 1 
          having c.country = 'USA'
          order by tracks_sold desc

It returns following result:

enter image description here

It is wrong. It should return instead below table:

enter image description here

When I write the query by first separating tracks sold in USA and then joining并通过流派进行分组,效果很好。我想知道为什么有子句在这里无法正常工作。

在下面,您可以使用我使用的列找到数据库的Outlook: enter image description here

Many thanks in advance!

I am working with Chinook database and would like to write a query that returns genres most sold in USA. My idea uses having clause and returns table which is wrong.

I've already written something that works that doesn't use having clause however I would like to understand why my idea with having clause does not work. :)

Here's my SQL query:

        select g.name, count(il.invoice_line_id) tracks_sold from genre g 
          inner join track t 
          on t.genre_id = g.genre_id
          inner join invoice_line il
          on il.track_id = t.track_id
          inner join invoice i
          on i.invoice_id = il.invoice_id
          inner join customer c
          on c.customer_id = i.customer_id
          group by 1 
          having c.country = 'USA'
          order by tracks_sold desc

It returns following result:

enter image description here

It is wrong. It should return instead below table:

enter image description here

When I write the query by first separating tracks sold in USA and then joining and grouping by genre it works fine. I wonder why having clause does not work here as I expected.

Below you can find outlook of the database with columns that I use:
enter image description here

Many thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文