如何为同一个表 n mysql 编写子查询



我有一个名为sample的数据库表。

create table sample(name varchar(50),  amount int(10));
insert into sample(name,amount) values('rose',1000);
insert into sample(name,amount) values('jhon',2000);
insert into sample(name,amount) values('rose',2000);
insert into sample(name,amount) values('rahel',1000);
insert into sample(name,amount) values('rose',3000);

我希望输出为,

+----------+----------+---------------+-----------+
+---rose---+--1000----+-------2000----+---3000----+
+---jhon---+--2000----+---------------+-----------+
+---rahel--+--1000----+---------------+-----------+

如何编写查询以获取上面的输出喜欢?

你需要

使用 group_concat(),下面的查询会给你输出

select name, group_concat(amount) from sample 
group by name 

你想要透视值,但没有用于透视的列。 您可以使用变量分配一个数字,然后使用条件聚合。 假设您需要另外三列:

select name,
       max(case when rn = 1 then amount end) as amount1,
       max(case when rn = 2 then amount end) as amount2,
       max(case when rn = 3 then amount end) as amount3
from (select s.*,
             (@rn := if(@n = name, @rn + 1,
                        if(@n := name, 1, 1)
                       )
             ) as rn
      from sample s cross join
           (select @n := '', @rn := 0) params
      order by name
     ) s
group by name;

您需要使用 GROUP_CONCAT() 函数,您的查询将在下面提及:

从样品中选择名称,GROUP_CONCAT(金额)按名称分组;

你会得到你想要的输出。

最新更新