MySQL将行合并到列中

时间:2016-09-19 09:59:58

标签: mysql sql

我做了一些研究,但仍然无法解决我的问题。

我在下一张图片链接中有这张表: Table Sample

我正在尝试编写一个查询,以便我可以获得类似此图片链接的内容: Sample I need

我确实尝试编写如下查询:

select ticket_pic, case when status = 'open' then count(tickets_id) end as open_ticket, case when status = 'close' then count(tickets_id) end as close_ticket from gt_tickets group by ticket_pic, status

但它返回了错误的数据 请指教。任何提示都会非常感激。

干杯

2 个答案:

答案 0 :(得分:1)

我不妨指出MySQL中最简单的语法是:

select ticket_pic,
       sum(status = 'open') as open_ticket,
       sum(status = 'close') as close_ticket 
from gt_tickets
group by ticket_pic;

MySQL将布尔表达式视为整数,在数字上下文中,使用" 0"为假和" 1"为了真实。

答案 1 :(得分:0)

select ticket_pic,
    SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) as open_ticket,
    SUM(CASE WHEN status = 'close' THEN 1 ELSE 0 END) as close_ticket      
from gt_tickets
group by ticket_pic

OR

select ticket_pic,
    COUNT(CASE WHEN status = 'open' THEN 1 ELSE NULL END) as open_ticket,
    COUNT(CASE WHEN status = 'close' THEN 1 ELSE NULL END) as   close_ticket        
from gt_tickets
group by ticket_pic