如何连接从一个组聚合的列值?

时间:2018-01-21 15:02:27

标签: mysql sql

我的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

它产生了这个结果:

enter image description here

专注于客户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条记录:

enter image description here

以红色圈出的2 PublicNotes因为汇总而被丢失。如何在丢失的PublicNotes与其分组记录连接时,如何维护我的第一个查询的分组?

1 个答案:

答案 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。这是你习惯的好习惯。
  • 不同音符的分隔符是竖线。你可以随意选择。