使用具有数据透视请求的分组

时间:2016-02-29 11:46:41

标签: mysql

这是我拥有的数据库:

| id | name    | type   | nom     | note |
|  1 | kiwi    | fruit  | Michel  |   14 |  
|  2 | kiwi    | fruit  | Jean    |    7 |  
|  3 | kiwi    | fruit  | Laurent |   18 |  
|  4 | fraise  | fruit  | Michel  |   10 |  
|  5 | fraise  | fruit  | Laurent |   12 |  
|  6 | poireau | legume | Michel  |   10 |

我想得到这样的结果:

| id       | name    | Michel | Jean | Laurent |
| kiwi     | fruit   |     14 |    7 |      18 |  
| fraise   | fruit   |     10 | NULL |      12 |  
| poireau  | legume  |     10 | NULL |    NULL |

因此,我尝试根据nomnote推送列nom,以使每个name拥有type

这不是我的真实数据库,我的静态编号不是nomnametypenote。一切都是动态的,所以我尝试了一种动态的方式来做到这一点

set @sql=null;  
select group_concat(distinct 'case when nom = ''', nom,''' then note end as ',replace(nom, ' ', '')) into @sql from products;  
set @sql = concat('select name, type, ', @sql, ' from products group by name, type');  
prepare stmt from @sql;  
execute stmt;  

结果:

|名字|类型|米歇尔|让|劳伦特|
| fraise |水果| 10 | NULL | NULL |
|猕猴桃|水果| 14 | NULL | NULL |
| poireau |豆类| 10 | NULL | NULL |

不幸的是,枢轴很好,但note属于Jean并且Laurent丢失了。

我在没有group by的情况下尝试了相同的请求。

set @sql=null;  
select group_concat(distinct 'case when nom = ''', nom,''' then note end as ',replace(nom, ' ', '')) into @sql from products;  
set @sql = concat('select name, type, ', @sql, ' from products');  
prepare stmt from @sql;  
execute stmt; 

结果:

|名字|类型|米歇尔|让|劳伦特|
|猕猴桃|水果| 14 | NULL | NULL |
|猕猴桃|水果| NULL | 7 | NULL |
|猕猴桃|水果| NULL | NULL | 18 |
| fraise |水果| 10 | NULL | NULL |
| fraise |水果| NULL | NULL | 12 |
| poireau |豆类| 10 | NULL | NULL |

name列不是群组,但所有note都在那里!

我想要什么,它是name的一个群组,所有note属于每个nom

感谢您的帮助!

答案:

  

设置@sql = null;
  选择group_concat(不同的' max(当nom =''',nom,'''''然后注意结束时)为' ,从产品中替换(nom,''''))到@sql;
  设置@sql = concat('选择名称,类型,',@ sql,'来自产品组的名称,类型');
  从@sql准备stmt;
  执行stmt;

0 个答案:

没有答案