SQL,join,子查询,派生表

时间:2016-04-12 13:39:00

标签: sql join

我有以下表格:

lead_id | status | list_id | user_id |
    1   |   ZP   |    1    |  2001   |
    2   |   ZP   |    2    |  2001   |
    3   |   ZP   |    2    |  2002   |
    4   |   ZP   |    1    |  2002   |
    5   |   ZP   |    1    |  2002   |

就像主表

现在有如下表格:

list_id | camp_id |
  1     | camp1   |
  2     | camp2   |

我希望得到以下结果:

user_id | camp1 | camp2 |
 2001   |   1   |   1   |
 2002   |   2   |   1   |

有没有办法实现它?

1 个答案:

答案 0 :(得分:0)

加入表并使用条件聚合。

select m.user_id
,sum(case when m.list_id = 1 then 1 else 0 end) as camp1
,sum(case when m.list_id = 2 then 1 else 0 end) as camp2
from mastertable m
join othertable o on o.list_id = m.list_id
group by m.user_id
相关问题