带有having子句的SQL查询返回意外结果
我正在与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:
It is wrong. It should return instead below table:
When I write the query by first separating tracks sold in USA and then joining并通过流派进行分组,效果很好。我想知道为什么有子句在这里无法正常工作。
在下面,您可以使用我使用的列找到数据库的Outlook:
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:
It is wrong. It should return instead below table:
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:
Many thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论