需要查询以特定格式显示

时间:2016-12-08 10:01:25

标签: mysql

我有两张表umarklist

SELECT * from u;
+------+-------+--------+-------+------------+
| id   | name  | adress | class | DOB        |
+------+-------+--------+-------+------------+
|    1 | Arun  | kollam |     6 | 1993-02-01 |
|    2 | Anoop | kollam |     6 | 1993-05-11 |
|    2 | Devi  | kollam |     6 | 1993-04-16 |
+------+-------+--------+-------+------------+

3 rows in set (0.02 sec)
 select * from marklist;
+------+-----------+------------+-------+--------+
| id   | subject   | markscored | outof | userid |
+------+-----------+------------+-------+--------+
|    1 | biology   |         37 |    50 |      1 |
|    2 | chemistry |         48 |    50 |      1 |
|    3 | physics   |         48 |    50 |      1 |
|    4 | biology   |         45 |    50 |      2 |
|    5 | chemistry |         41 |    50 |      2 |
|    6 | physics   |         34 |    50 |      2 |
|    7 | biology   |         39 |    50 |      3 |
|    8 | chemistry |         46 |    50 |      3 |
|    9 | physics   |         48 |    50 |      3 |
+------+-----------+------------+-------+--------+
9 rows in set (0.00 sec)

从这两个表中我需要一个输出:

+------+------+---------+-----------+---------+----------------+------------+
| name |class | biology | chemistry | physics | totlmarkscored | percentage |
+------+------+---------+-----------+---------+----------------+------------+

2 个答案:

答案 0 :(得分:0)

SELECT u.name, u.class, marklist.subject as biology, marklist.subject as chemistry, marklist.subject as physics, marklist.totlmarkscored, marklist.percentage
FROM u
INNER JOIN marklist
ON u.id=marklist.id

随意编辑我的错误!

答案 1 :(得分:0)

SELECT t1.name,
       t1.class,
       t2.biology,
       t2.chemistry,
       t2.physics,
       COALESCE(t2.biology, 0) + COALESCE(t2.chemistry, 0) +
           COALESCE(t2.physics, 0) AS totlmarkscored,
       100*(COALESCE(t2.biology, 0) + COALESCE(t2.chemistry, 0) +
           COALESCE(t2.physics, 0)) /
       (COALESCE(t2.outofbiology, 0) + COALESCE(t2.outofchemstry, 0) +
        COALESCE(t2.outofphysics, 0)) AS percentage
FROM u t1
INNER JOIN
(
    SELECT userid,
           MAX(CASE WHEN subject = 'biology'   THEN markscored END) AS biology,
           MAX(CASE WHEN subject = 'biology'   THEN outof END)      AS outofbiology,
           MAX(CASE WHEN subject = 'chemistry' THEN markscored END) AS chemistry,
           MAX(CASE WHEN subject = 'chemistry' THEN outof END)      AS outofchemistry,
           MAX(CASE WHEN subject = 'physics'   THEN markscored END) AS physics,
           MAX(CASE WHEN subject = 'physics'   THEN outof END)      AS outofphysics,
    FROM marklist
    GROUP BY userid
) t2
    ON t1.id = t2.userid
相关问题