mysql中单个表的多个结果

时间:2011-12-14 22:54:21

标签: sql self-join mysql-5.0

我的数据库中有一个包含列的表:

Lead_id INT(11) PRIMARY KEY NOT NULL
user_id INT(11)
lead_status ENUM('active','win','loss')

以下示例数据:

Lead_id     user_id     lead_status
   1          45         active
   2          31         win
   3          11         loss
   4          45         win
   5          11         active
   6          45         loss

我需要查询上面的表格以获得以下输出:

user_id      total_leads      active     win     loss
   45             3              1        1        1
   31             1              0        1        0
   11             2              1        0        1

我打算以图形方式表示输出表中的数据。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT
    user_id,
    COUNT(*) AS total_leads,
    SUM(lead_status = 'active') AS active,
    SUM(lead_status = 'win') AS win,
    SUM(lead_status = 'loss') AS loss
FROM your_table
GROUP BY user_id