如何从SQL中的3个以上的表中求和

时间:2016-03-11 08:12:12

标签: mysql

我有4张桌子作为轰鸣声

table : user

id_tkn  |   nm_user     |
-----------------------------------------
    1   |   belva       |
    2   |   nanda       |
    3   |   maya        |
-----------------------------------------

table : maintenance

id_mntnc|id_tkn |   sts |   date    |
-----------------------------------------------------------------
    1   |   2   |   1   |2016-03-03 |
    2   |   2   |   2   |2016-03-03 |
    3   |   1   |   1   |2016-03-03 |
    4   |   2   |   0   |2016-03-03 |
    5   |   2   |   1   |2016-03-03 |
-----------------------------------------------------------------

table : Installasi

id_istlsi|id_tkn|   sts |   date    |
-----------------------------------------------------------------
    1   |   2   |   1   |2016-03-03 |
    2   |   1   |   1   |2016-03-03 |
    3   |   1   |   1   |2016-03-03 |
    4   |   2   |   1   |2016-03-03 |
    5   |   3   |   1   |2016-03-03 |
-----------------------------------------------------------------

table : visit

id_vst  |id_tkn |   sts |   date    |
-----------------------------------------------------------------
    1   |   2   |   1   |2016-03-03 |
    2   |   2   |   0   |2016-03-03 |
    3   |   1   |   1   |2016-03-03 |
-----------------------------------------------------------------

有关'sts'列的信息         0 - >有待         1 - >成功         2 - >失败。 从上面的表中,我想按状态(sts)加上id_tkn = 2,结果如下表所示,如何生成SQL命令来生成下表?

id_tkn  |   nm_usr  | maintenance_suc | maintenance_fail | installasi_suc| installasi_fail | visit_suc| visit_fail
-----------------------------------------------------------------------------------------------------------------------
   2    |   nanda   |      2           |       1         |     2         |     0           |     1    |  0

1 个答案:

答案 0 :(得分:0)

这应该正常,但可能需要优化:

select 
    u.id_tkn, 
    u.nm_user,
    sum ( case when stat.sts = 1 and stat.typ = 'm' then 1 else 0 end ) as maintenance_suc,
    sum ( case when stat.sts = 2 and stat.typ = 'm' then 1 else 0 end ) as maintenance_fail,
    sum ( case when stat.sts = 1 and stat.typ = 'i' then 1 else 0 end ) as installasi_suc,
    sum ( case when stat.sts = 2 and stat.typ = 'i' then 1 else 0 end ) as installasi_fail,
    sum ( case when stat.sts = 1 and stat.typ = 'v' then 1 else 0 end ) as visit_suc,
    sum ( case when stat.sts = 2 and stat.typ = 'v' then 1 else 0 end ) as visit_fail
from
user u
left join 
(
    select sts, 'm', id_tkn
    from 
    maintenance
    union all
    select sts, 'i', id_tkn
    from 
    Installasi
    union all
    select sts, 'v', id_tkn
    from 
    visit
) stat on u.id_tkn = stat.id_tkn
where u.id_tkn = 2
group by u.id_tkn, u.nm_user