mysql使用groupby时如何给不匹配的列赋值

zsbz8rwp  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(430)

我有下面的movietheatertbl表:

Name      Location      Date    TicketRevenue  SnackRevenue  BeverageRevenue
AMC       Alpine St.    8/14        100             80             60
Atlas     Main St.      8/19        300             150            100
Atlas     Lincoln Rd.   8/19        50              50             40

我想将这些数据插入一个名为summarytbl的表中,该表应该显示按电影院名称分组的revenue列的总和。如果同名行的其他列不相同(例如2个atlas条目中的位置不同),我希望在该位置显示空值。这就是我希望summarytbl的样子:

Name      Location      Date    TicketRevenue  SnackRevenue  BeverageRevenue
AMC       Alpine St.    8/14        100             80             60
Atlas                   8/19        350             200           140

以下是我当前使用的代码:

insert into  SummaryTbl (Name,Location,Date,TicketRevenue,SnackRevenue,BeverageRevenue)
select Name,Location,Date,sum(TicketRevenue),sum(SnackRevenue), sum(BeverageRevenue)
from MovieTheaterTbl
group by Name

这可以很好地将数据分组在一起,但是当一个电影院有多个位置时,它不会在位置字段中插入空值。有人能解释一下怎么做吗?谢谢您!

balp4ylt

balp4ylt1#

试试这个:

insert into  SummaryTbl (Name,Location,Date,TicketRevenue,SnackRevenue,BeverageRevenue)
select Name, if(count(distinct Location)=1, Location, NULL), Date,sum(TicketRevenue),sum(SnackRevenue), sum(BeverageRevenue)
from MovieTheaterTbl
group by Name
klsxnrf1

klsxnrf12#

你可以使用联合和有。。如果count(*)>1,则插入null,否则插入位置

insert into  SummaryTbl (Name,Location,Date,TicketRevenue,SnackRevenue,BeverageRevenue)
  select Name, NULL,Date,sum(TicketRevenue),sum(SnackRevenue), sum(BeverageRevenue)
  from MovieTheaterTbl
  group by Name
  HAVING COUNT(*) >1
  and count(location) >1
  UNION
  select Name, Location,Date,sum(TicketRevenue),sum(SnackRevenue), sum(BeverageRevenue)
  from MovieTheaterTbl
  group by Name
  HAVING COUNT(*) =1
  AND count(location) = 1

相关问题