MySQL组由没有聚合时

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

我有一张叫做booking_details的桌子。

id  |   tour_id |   tour_fee|   booking_id
1   |   1       |   200     |   1
2   |   2       |   350     |   1
3   |   1       |   200     |   2
4   |   2       |   350     |   3

tour_id指的是Tours表,而booking_id指的是Bookings表。我想得到这样的报告

tour_id 1指纽约之旅tour_id 2指巴黎之旅

我需要生成这样的报告

tour name    |  total_income    |   number_of_bookings
New york tour|  400             |        2
Paris tour   |  700             |        2

这里基本上是您的名字,该旅游的总收入和该旅游的预订数量。

我现在所做的就是这个。但这给了我一个语法错误。看来我不能按结果分组。

SELECT booking_details.*,Tours.name as name, count(Tours.id) FROM booking_details
inner join Tours on
booking_details.tour_id = Tours.id group by Tours.name;

我如何使用MySQL实现这一目标?

mysql sql
3个回答
0
投票

您在查询中使用了聚合count(),并且根据您的要求,它显示您需要聚合。当您使用聚合时,您还必须将选择列也放在组中

   SELECT Tours.name as name,sum(tour_fee) income, count(Tours.id) 
   FROM booking_details
    inner join Tours on
    booking_details.tour_id = Tours.id group by Tours.name

正如您在选择booking_details.*中所使用的那样,这意味着预订表的每一列,但您没有将这些列放入组中,因此抛出错误


0
投票

您正在尝试选择不属于GROUP BY子句的非聚合列。

更改您的查询,如下所示。

SELECT t.NAME           AS NAME, 
       Sum(bd.tour_fee) total_income, 
       Count(t.id)      number_of_bookings 
FROM   booking_details bd 
       INNER JOIN tours t 
               ON bd.tour_id = t.id 
GROUP  BY t.NAME; 

小建议,作为一种好的做法,您应该在加入时使用表的别名。


0
投票

除聚合字段外,您需要在组中添加所有其他列

SELECT 
    booking_details.tour_id, 
    Tours.name AS name, 
    SUM(tourfee) AS total_income,
    COUNT(Tours.id) 
FROM 
    booking_details
INNER JOIN
    Tours ON booking_details.tour_id = Tours.id 
GROUP BY
    booking_details.tour_id, Tours.name
© www.soinside.com 2019 - 2024. All rights reserved.