MySql Group with Pivot

时间:2014-09-30 12:48:32

标签: mysql sql group-by pivot

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

SELECT * FROM StudentInfo;

enter image description here

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

enter image description here

4 个答案:

答案 0 :(得分:0)

您需要创建一个数据透视表,这里有一个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

您可以根据需要修改此项,以获得所需的结果。

答案 1 :(得分:0)

这应该做你想要的:

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;

答案 2 :(得分:0)

尝试以下:

      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

答案 3 :(得分:0)

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