以所需格式显示相同表的行

时间:2017-10-30 05:48:33

标签: mysql join group-by sum where

从以下格式

pic1

到这个

To this ;

我可以到达这里;

I could achieve till here using "with" clause

如果可以通过两个步骤实现所需的格式,请提出建议。

1 个答案:

答案 0 :(得分:0)

我猜你试图将a,b,a和b与子总数分组。在下面的代码中,我找出了每个id落入哪个组,然后创建了一个带有一些虚拟值的联合来获取子总数。

/*
drop table if exists t;
create table t(id varchar(5), type varchar(1), value int);

insert into t values
('one','a',1),('one','b',1),
('ten','a',1),('ten','b',1),
('two','a',1),('three','a',1),
('four','b',1),('five','b',1),
('six','a',1),('seven','b',1);
*/
select 
        case when id like 'zzz%' then 'total' else id end as idout,
        case when type = 'xxx' then '' else type end as typeout,
        value 
from
(
select t.* ,
        case when t.type <> t1.type then 1 
              when t.type = 'a' then 2
            else 3
        end as st
from t
left join t t1 on t1.id = t.id and t1.type <> t.type
union all
(
select concat('zzz',st) id,'xxx' type, 
        sum(value), st
from
(
select t.* , t1.type t1type,
        case when t.type <> t1.type then 1 
              when t.type = 'a' then 2
            else 3
        end as st
from t
left join t t1 on t1.id = t.id and t1.type <> t.type
) s
group by concat('zzz',st) ,'xxx',st
)
) t
order by st,id

结果

+-------+---------+-------+
| idout | typeout | value |
+-------+---------+-------+
| one   | b       |     1 |
| one   | a       |     1 |
| ten   | b       |     1 |
| ten   | a       |     1 |
| total |         |     4 |
| six   | a       |     1 |
| three | a       |     1 |
| two   | a       |     1 |
| total |         |     3 |
| five  | b       |     1 |
| four  | b       |     1 |
| seven | b       |     1 |
| total |         |     3 |
+-------+---------+-------+
13 rows in set (0.00 sec)