问题
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