search

Home  >  Q&A  >  body text

java - mysql query, how to query this

I saw an interview question posted by someone else in the group, =. =, how to query?

世界只因有你世界只因有你2714 days ago755

reply all(4)I'll reply

  • 黄舟

    黄舟2017-06-22 11:56:36

    The title picture is Chinase, click here.
    Course determined case:
    CASE implementation:

    SELECT
        `Name`,
        MAX(
            CASE
            WHEN Course = 'Chinase' THEN
                Score
            END
        ) AS Chinase,
        MAX(
            CASE
            WHEN Course = 'Math' THEN
                Score
            END
        ) AS Math,
        MAX(
            CASE
            WHEN Course = 'English' THEN
                Score
            END
        ) AS English
    FROM
        table1
    GROUP BY
        `Name`

    IF implementation:

    SELECT
        `Name`,
    
    SUM(IF (Course = 'Chinase', Score, 0)) AS Chinase,
    
    SUM(IF (Course = 'Math', Score, 0)) AS Math,
    
    SUM(IF (Course = 'English', Score, 0)) AS English
    
    FROM
        table1
    GROUP BY `Name`

    Course is not sure, use dynamics:

    SET @CC='';
    SELECT @CC:=CONCAT(@CC,'SUM(IF(Course=\'',Course,'\'',',Score,0)) AS ',Course,',') FROM (SELECT DISTINCT Course FROM table1) A;
    SET @HH=CONCAT('SELECT Name,',LEFT(@CC,LENGTH(@CC)-1),' FROM table1 GROUP BY Name');
    PREPARE stmt FROM @HH;
    EXECUTE stmt;

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-22 11:56:36

    select name, sum(case when Course='Chinese' then Score end) as Chinese,
    sum(case when type='Math' then Score end) as Math,
    sum(case when type='English' then Score end) as English
    from table1
    group by name

    reply
    0
  • PHP中文网

    PHP中文网2017-06-22 11:56:36

    You should learn the principle
    Baidu "mysql row column conversion"
    It is useless to only learn this sql

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-22 11:56:36

    This kind of god-like sql is used when doing data statistics. It is not used in normal PHP work.

    reply
    0
  • Cancelreply