table1是
class_name subject_Name
I class telugu
I class hindi
II class telugu
II class hindi
table2是
exam_name telugu hindi
unit 1 25 35
unit 2 30 35
现在我在table1中插入一行主题数学。该主题已添加到table2作为列,并检查主题(数学)是否存在于table2中。
我的所需输出
table1是
class_name subject_Name
I class telugu
I class hindi
II class telugu
II class hindi
II class maths
III class hindi
III class telugu
III class maths
table2是
exam_name telugu hindi maths
unit 1 25 35 35
unit 2 30 35 25
提前致谢....
答案 0 :(得分:2)
我将重组表2以使用以下列对其进行标准化:
EXAM_NAME, 主题,得分
使用主键exam_name,主题
然后,您可以查询它以获得不同科目的所有分数。
表:
mysql> SELECT * FROM t2;
+-----------+---------+-------+
| exam_name | subject | score |
+-----------+---------+-------+
| unit1 | hindi | 25 |
| unit1 | telugu | 45 |
| unit2 | math | 15 |
| unit2 | telugu | 25 |
+-----------+---------+-------+
您现在可以查询: 首先,您需要找出所有科目:
SELECT DISTINCT subject from t2;
现在您可以使用主题创建数据透视表:
SELECT exam_name, details.hindi, details.telugu, details.math
FROM (
SELECT exam_name,
SUM(if(subject='hindi',score,0)) AS hindi,
SUM(if(subject='telugu', score, 0)) AS telugu,
SUM(if(subject='math', score, 0)) AS math
FROM t2 GROUP BY exam_name
) AS details ;
+-----------+-------+--------+------+
| exam_name | hindi | telugu | math |
+-----------+-------+--------+------+
| unit1 | 25 | 45 | 0 |
| unit2 | 0 | 25 | 15 |
+-----------+-------+--------+------+
查找数据透视表以获取更多详细信息。此解决方案假定表中每个exam_name / subject组合只有一个条目。
您可以在一个复杂查询中组合这两个步骤。取决于您是否从脚本中调用此脚本,这可能是也可能不是更好。