MySql Group by 与 Pivot

Posted

技术标签:

【中文标题】MySql Group by 与 Pivot【英文标题】:MySql Group by with Pivot 【发布时间】:2014-09-30 12:48:32 【问题描述】:

我在 mysql 中有一个表(比如 studentinfo)。

SELECT * FROM StudentInfo;

我想要以下输出而不使用任何额外或临时表。 (可能正在使用 group by 和 pivot)

【问题讨论】:

你尝试过什么来达到你想要的输出?尝试修改您的问题。 我很困惑将 group by 和 pivot 结合起来,我自己就卡在那里了。 【参考方案1】:

你需要创建一个数据透视表,这里有一个link,里面有很多很好的例子。

基本上,你会做这样的事情

 SELECT Rollnumber, 
        property
      CASE WHEN Property="Name" then Property end as Name,
      CASE WHEN Property="Year" then Property end as Year,
      CASE WHEN Property="City" then Property end as City,
 FROM whatever_table
 GROUP BY Rollnumber

您可以随意修改它,以获得您想要的结果。

【讨论】:

【参考方案2】:

这应该做你想做的:

select si.Rollnumber, 
       max(case when si.Property = 'Name' then si.Value end) as Name,
       max(case when si.Property = 'Year' then si.Value end) as Year,
       max(case when si.Property = 'City' then si.Value end) as City
from StudentInfo si
group by si.Rollnumber;

【讨论】:

【参考方案3】:

试试下面:

      select * from (SELECT A.Rollnumber,if(A.Property='Name',Value,
        (select B.Value from StudentInfo B where B.Property='Name' and B.Rollnumber=A.Rollnumber LIMIT 1)) as Name,
        if(Property='Year',Value,
        (select B.Value from StudentInfo B where B.Property='Year' and B.Rollnumber=A.Rollnumber LIMIT 1)) as Year,
       if(Property='City',Value,
        (select B.Value from StudentInfo B where B.Property='City' and B.Rollnumber=A.Rollnumber LIMIT 1)) 
         as City 
         FROM StudentInfo A) Temp group by Rollnumber

【讨论】:

【参考方案4】:
SELECT
    name.rollnumber,
    name.value AS name,
    year.value AS year,
    city.value AS city
FROM 
    StudentInfo name
    INNER JOIN StudentInfo year ON name.rollnumber = year.rollnumber
    INNER JOIN StudentInfo city ON name.rollnumber = city.rollnumber    
WHERE
    name.property = 'name' AND
    year.property = 'year' AND
    city.property = 'city' AND

【讨论】:

以上是关于MySql Group by 与 Pivot的主要内容,如果未能解决你的问题,请参考以下文章

MYSQL SELECT 与 GROUP。想要限制 GROUP BY 中返回元素的数量

浅析MySQL使用 GROUP BY 分组聚合与细分聚合

MySQL 查询优化与 group by 和 order by rand

MySQL:条件 MIN() 与 GROUP BY

mysql_group by与聚合函数order by联合使用

MySql Group by 与 Pivot