将多列转换为一行mysql

时间:2016-08-17 10:17:04

标签: mysql sql transpose workbench

create table tab_1(
t1 decimal (10),
t2 decimal (10),
t3 decimal (10)
);

insert into tab_1(t1, t2, t3)
values(1,-2,-5);
insert into tab_1(t1, t2, t3)
values(-3,4,6);
insert into tab_1(t1, t2, t3)
values(5,1,2);

select @sum1:=sum(t1) FROM tab_1 WHERE t1 > 0
select @sum2:=sum(t2) FROM tab_1 WHERE t2 > 0
select @sum3:=sum(t3) FROM tab_1 WHERE t3 > 0

select @sum1, @sum2, @sum3;

结果:

 @sum1  @sum2 @sum3
 ------------------
  6      5      8

我有上面的查询,我想要一个查询,将列转换为一列和三行,如下所示:

Sum
--
6
5
8

我使用MySQL Workbench 6.3.7。

2 个答案:

答案 0 :(得分:0)

您可以通过UNION ALL

实现这一目标
SELECT SUM(IF(t1 > 0 , t1, 0)) AS sum  FROM tab_1
UNION ALL
SELECT SUM(IF(t2 > 0 , t2, 0)) AS sum  FROM tab_1
UNION ALL
SELECT SUM(IF(t3 > 0 , t3, 0)) AS sum  FROM tab_1

UNION vs UNION ALL

修改

为了将结果存储在变量中: confused.why,你需要这个吗?

SET @sum1 := 0;
SET @sum2 := 0;
SET @sum3 := 0;
SELECT @sum1 := SUM(IF(t1 > 0 , t1, 0)) AS sum   FROM tab_1
UNION ALL
SELECT @sum2:= SUM(IF(t2 > 0 , t2, 0)) AS sum FROM tab_1
UNION ALL
SELECT @sum3 := SUM(IF(t3 > 0 , t3, 0)) AS sum  FROM tab_1;

SELECT @sum1,@sum2,@sum3;

答案 1 :(得分:0)

您的变量分配几乎就在那里。只需将union all放在它们之间:

select 't1', sum(t1) FROM tab_1 WHERE t1 > 0
union all
select 't2', sum(t2) FROM tab_1 WHERE t2 > 0
union all
select 't3', sum(t3) FROM tab_1 WHERE t3 > 0;

(我删除了变量赋值,因为这似乎没什么必要。)

我会包含一个标识符,因此我知道哪个值对应于哪个列。