2张表A和B A是主表 关联字段 A:visit_id B:visitId
2表数据如下:
A:                                     
visit_id    name   text
   1        张三    a
   2        李四    a
   3        王五    b
   4        张三    a
B:
visitId     typeId
   1            65
   1            14
   2            65
   2            14
   3            65
   3            14
   2            14
想要得到结果集:
 name  visit_id次数     14汇总次数        65汇总次数     text汇总次数
 张三      2                  1               1             2
 李四      1                  2               1             1
 王五      1                  1               1             1

解决方案 »

  1.   


    with a(                           
    visit_id,    name,   text)as(
    select   1,        '张三',    'a' union all
    select   2,        '李四',    'a' union all
    select   3,        '王五',    'b' union all
    select   4,        '张三',    'a'),
    B(
    visitId,     typeId)as(
    select   1,            65 union all
    select   1,            14 union all
    select   2,            65 union all
    select   2,            14 union all
    select   3,            65 union all
    select   3,            14 union all
    select   2,            14)
    select  
    name,COUNT(distinct visit_id),
    COUNT(case when typeId=14 then 1 else null end),
    COUNT(case when typeId=65 then 1 else null end),
    (select COUNT(text) from a where name=c.name)
    from B full join a  c on c.visit_id=B.visitId
    group by name