2015-12-06 47 views
0

我有一個表,看起來像這樣: Table合併2行成一排,用2列MYSQL

然而,問題是,與其說帕特里夏有13票和1個電影票在同一行,它分成不同的行。

我想我需要做一個數據透視表,但我不知道我到底需要做什麼。

這是我到目前爲止的代碼:

select customer.hippcode, customer.LastName, customer.Firstname, customer.Email, 
count(ticketdetails.eventtype) as 'Theater Tickets', 
0 as 'Movie Tickets' 
from customer 
inner join ticketdetails on ticketdetails.hippcode = customer.hippcode 
where ticketdetails.hippcode is not null 
and ticketdetails.eventType ='T' 
Group by Customer.hippcode 
union 
select customer.hippcode, customer.LastName, customer.Firstname, customer.Email, 
0, count(ticketdetails.eventtype) as 'Movie Tickets' 
from customer 
inner join ticketdetails on ticketdetails.hippcode = customer.hippcode 
where ticketdetails.hippcode is not null 
and ticketdetails.eventType ='M' 
Group by Customer.hippcode 
order by `theater tickets` + `movie tickets` desc; 

感謝您的幫助提前。

回答

0

你可以嘗試這樣的事:

select 
    customer.hippcode, customer.LastName, customer.Firstname, customer.Email, 
    count(case when ticketdetails.eventtype = 'T' then 1 else 0 end) as TheaterTickets, 
    count(case when ticketdetails.eventtype = 'M' then 1 else 0 end) as MovieTickets 
from customer 
inner join ticketdetails on ticketdetails.hippcode = customer.hippcode 
where ticketdetails.hippcode is not null 
and ticketdetails.eventType in ('T', 'M') 
Group by customer.hippcode, customer.LastName, customer.Firstname, customer.Email 
Order by TheaterTickets+MovieTickets desc; 
+0

太感謝你了,它的工作!並感謝您的快速響應。 – ACP