mysql - 将2行合并为一行,使用2列MYSQL

标签 mysql sql sql-server pivot

我有一个看起来像这样的表: Table

但是,问题在于,Patricia 有 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;

感谢您提前提供的帮助。

最佳答案

你可以尝试这样的事情:

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;

关于mysql - 将2行合并为一行,使用2列MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113925/

相关文章:

sql-server - 如何将值转换为列并将计数放入其中?

mysql - 如何在插入值存在的地方替换主键?

php - 计算表中的项目

MySQL - 用字符替换第一个空格

mysql - 使用列数据作为列名的查询

mysql - 如果 ACID 属性定义明确,为什么我们有/接受不同的事务级别?

sql-server - SQL 查询中的累积列

MySQL 与 SQL 的区别

mysql - 删除 MySQL 选择

MySQL 删除函数在存储过程中不起作用