简体   繁体   中英

How to transform results of an sql query to an html table with specific format

I am trying to create some statistics for a library reservation system. The result of my sql query looks like the following structure.

total_no_students| department  | property       | month  
 241             | Physics     | undergraduate  | Nov
 236             | Physics     | undergraduate  | Dec
 254             | Physics     | postgraduate   | Nov
 210             | Physics     | postgraduate   | Dec
 193             | Architecture| undergraduate  | Nov
 181             | Architecture| undergraduate  | Dec
 127             | Architecture| postgraduate   | Nov
 292             | Architecture| postgraduate   | Dec
 134             | Biology     | undergraduate  | Nov
 188             | Biology     | undergraduate  | Dec
 129             | Biology     | postgraduate   | Nov
 219             | Biology     | postgraduate   | Dec

I am trying using php to write some code in order to create a statistics table with the following appearance:

|Physics-undergrad|Physics-postgrad|Architecture-undergrad|Architecture-postgrad|
Nov |      241        |     254        |         193          |        127          |
Dec |      236        |     210        |         181          |        292          |

Any help how to trasform the query using php to the above table? Thanks a lot!

Try this:

SELECT A.month, 
       SUM(CASE WHEN A.department = 'Physics' AND A.property = 'undergraduate' THEN A.total_no_students ELSE 0 END) AS Physics_undergraduate, 
       SUM(CASE WHEN A.department = 'Physics' AND A.property = 'postgraduate' THEN A.total_no_students ELSE 0 END) AS Physics_postgraduate, 
       SUM(CASE WHEN A.department = 'Architecture' AND A.property = 'undergraduate' THEN A.total_no_students ELSE 0 END) AS Architecture_undergraduate, 
       SUM(CASE WHEN A.department = 'Architecture' AND A.property = 'postgraduate' THEN A.total_no_students ELSE 0 END) AS Architecture_postgraduate, 
       SUM(CASE WHEN A.department = 'Biology' AND A.property = 'undergraduate' THEN A.total_no_students ELSE 0 END) AS Biology_undergraduate, 
       SUM(CASE WHEN A.department = 'Biology' AND A.property = 'postgraduate' THEN A.total_no_students ELSE 0 END) AS Biology_postgraduate
FROM (...Your Existing Query...) AS A 
GROUP BY A.month

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM