MySQL How to assign a null value to non matching columns when using Group By

断了今生、忘了曾经 提交于 2019-12-24 05:27:10

问题


I have the following MovieTheaterTbl table:

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 

I would like to insert this data into a table called SummaryTbl, which should display the sum of the Revenue columns, grouped by the movie theater name. If any of the other columns are not identical for rows with the same name (for example the location differs in the 2 Atlas entries), I would like a null value to be displayed in that spot. This is what I'd like SummaryTbl to look like:

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

Here is the code that I'm currently using:

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

This groups the data together just fine, but it does not insert a NULL value in the Location field when a single movie theater has multiple locations. Could someone please explain how to do this? Thank you!


回答1:


Try this:

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



回答2:


You can use union adn having .. having count(*) > 1 insert null else insert the location

  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


来源:https://stackoverflow.com/questions/39882439/mysql-how-to-assign-a-null-value-to-non-matching-columns-when-using-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!