【问题标题】:MySQL SUM, INNER JOIN and GROUP BY in the same statement. Syntax errorMySQL SUM、INNER JOIN 和 GROUP BY 在同一个语句中。语法错误
【发布时间】:2019-07-09 08:48:36
【问题描述】:

我需要从这四个表中得到每个艺术家的总销售额:

Artists (artist.id, artist.name)
Events (events.id, events.title, events.artist_id)
Sales (sales.events_id, sales.buyer_id, sales.amount)
Buyer (buyer.id, buyer.name)

我需要以下语句加入三个表:

SELECT sales.amount as SalesTotal, artists.title AS Artist
SUM (SalesTotal) 
FROM sales
INNER JOIN events ON events.id = sales.event_id
INNER JOIN artists ON artists.id = events.artist_id
GROUP BY Artist

但我总是遇到语法错误。我已经用谷歌搜索了它,但我得到的所有示例都在同一张表中。 我不知道错误应该在哪里。任何帮助将不胜感激

【问题讨论】:

  • 其实应该是SUM(sales.amount) as SalesTotal, artists.title AS Artist

标签: mysql sum inner-join


【解决方案1】:

它将返回所有艺术家列表,其中包含总销售额 + 空艺术家:

SELECT artists.title AS Artist, SUM(SalesTotal) as SalesTotal
FROM artists
LEFT JOIN events ON events.artist_id = artists.artist_id
LEFT JOIN sales ON sales.event_id = events.event_id
GROUP BY artists.id

输出:

Artist   SaleTotal
abc      2000
pqr      NULL
xyz      100

【讨论】:

    【解决方案2】:

    我想你想要这个:

    SELECT 
         SUM(sales.amount) as SalesTotal, 
         artists.title AS Artist
    FROM sales
    INNER JOIN events ON events.id = sales.event_id
    INNER JOIN artists ON artists.id = events.artist_id
    GROUP BY artists.title;
    

    您不能在 group by 子句中使用别名,因为您的语句中不同子句的评估或执行顺序。在应用列列表中的别名定义之前执行 group by 子句。

    【讨论】:

    • 可以在group by子句中使用别名
    • @HarshilDoshi 好吧,不完全是stackoverflow.com/questions/3841295/sql-using-alias-in-group-by,有些系统允许这样做。但它不应该工作,也不应该被使用!
    • 对不起。我对order by 子句感到困惑。谢谢!
    • 它只会给你那些有销售的艺术家......它不会导致空艺术家销售
    猜你喜欢
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多