Search code examples
mysqlsqlnullgroup-byinsert-into

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


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!


Solution

  • 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