例如,我有一个名为'stdinfo'的表,如
Id Name Mark
-----------------
1 Helal 10
2 Shakil 15
... ... ...
... ... ...
... ... ...
现在我想转换表格结果如下
Name Helal Shakil ...
----------------------
Id 1 2 ...
Mark 10 15 ...
有一个重要的事情是行数不固定。
请任何人帮我写sql查询来获得这个结果。
先谢谢...
答案 0 :(得分:0)
You can try this,
Table
--------------------------------------------------
subject_id subjectname classid teacher_id
---------------------------------------------------
3 Math 3 T-1
4 Economics 4 T-1
5 Physcis 3 T-1
--------------------------------------------------
Query:
SELECT sum( if( subjectname = 'Math', subject_id, 0 ) ) AS 'Economics',
sum( if( subjectname = 'Economics', subject_id, 0 ) ) AS 'Math',
sum( if( subjectname = 'Physcis', subject_id, 0 ) ) AS 'Physcis'
FROM tbsubject group by subjectname
Output:
----------------------------
Math Economics Physcis
---------------------------
0 4 0
3 0 0
0 0 5
----------------------------
Or you can create a view by programming.more example see pivot table
http://www.krishnasunuwar.com.np/2011/02/crosstab-query-pivot-table-or-transformation-of-rows-into-columns/