用于显示查询字段的sql

时间:2013-12-20 15:51:57

标签: mysql sql

我编写了一个sql来获取每个用户在数据库中的票证信息。

select u.realname,count(t.id) as ct,t.Status
from Tickets t,Users u
where u.id=t.Owner and (t.status='New' or t.status='Stalled' or t.status='Open')
group by u.realname,t.status;

它提供这样的输出

| Enoch Root           |     1 | new     |
| Enoch Root           |     1 | stalled |
| xyz   Chan           |     1 | open    |
| Jim                  |    22 | stalled |

但我正在寻找的是用户反对状态

       open   stalled  new
 root    1       10      14

请告诉我

2 个答案:

答案 0 :(得分:0)

SELECT
  u.realname,
  SUM(t.status='Open') AS `Open`,
  SUM(t.status='Stalled') AS `Stalled`,
  SUM(t.status='New') AS `New`
FROM Tickets t INNER JOIN Users u
     ON u.id=t.Owner
WHERE (t.status='New' OR t.status='Stalled' OR t.status='Open')
GROUP BY
  u.id, u.realname

答案 1 :(得分:0)

select u.realname, 
  sum( if( t.status = 'New', 1, 0 ) ) as new, 
  sum( if( t.status = 'Stalled', 1, 0 ) ) as stalled, 
  sum( if( t.status = 'Open', 1, 0 ) ) as open
from Tickets t, Users u
where 
  u.id = t.Owner and 
  t.status in ( 'New', 'Stalled', 'Open' )
group by u.realname