我的MySQL查询几乎完全
select ConfirmationNumber, ReservationDate, ifnull(CASE TableNumber WHEN 0 THEN 'UNASSIGNED' ELSE TableNumber END,'UNASSIGNED') AS 'Table', CONCAT(LastName, ', ', FirstName) AS 'Customer', Email, Phone, PublicNotes, sum(SleighSeats) + sum(CabSeats) AS Seats
from Reservations
where ReservationDate = '2018-1-25'
and ConfirmationNumber IS NOT NULL
and CancelDate IS NULL
group by TableNumber, Customer
order by TableNumber
它产生了这个结果:
专注于客户Corbosie ......上面。
因为正在进行分组,所以我缺少PublicNotes
个数据,因为某些记录正在从查询中压缩出来。我只是想从查询中包含的所有记录中连接PublicNotes
,包括那些被聚合出来的记录。
例如,当我以这种方式查询时:
select ConfirmationNumber, ReservationDate, ifnull(CASE TableNumber WHEN 0 THEN 'UNASSIGNED' ELSE TableNumber END,'UNASSIGNED') AS 'Table', CONCAT(LastName, ', ', FirstName) AS 'Customer', Email, Phone, PublicNotes, SleighSeats + CabSeats AS Seats
from Reservations
where ConfirmationNumber in ('092550', '764352', '661800')
...它显示了在第一个查询中压缩成1条记录(由于分组)的3条记录:
以红色圈出的2 PublicNotes
因为汇总而被丢失。如何在丢失的PublicNotes
与其分组记录连接时,如何维护我的第一个查询的分组?
答案 0 :(得分:1)
我想你想要group_concat()
:
select ConfirmationNumber, ReservationDate,
(CASE TableNumber WHEN 0 THEN 'UNASSIGNED' ELSE TableNumber END) AS "Table",
CONCAT(LastName, ', ', FirstName) AS Customer,
Email, Phone,
GROUP_CONCAT(PublicNotes, '|'),
(SUM(SleighSeats) + SUM(CabSeats)) AS Seats
from Reservations
where ReservationDate = '2018-1-25' and
ConfirmationNumber IS NOT NULL and
CancelDate IS NULL
group by ConfirmationNumber, ReservationDate, TableNumber, Customer, email, phone
order by TableNumber;
注意:
TableNumber
可以是NULL
,所以我删除了IFNULL()
。如果可以,请将其重新添加(或使用COALESCE()
。GROUP BY
。这是你习惯的好习惯。