简体   繁体   中英

MS access 2010 SQL query Help

How can i turn a table from this form:

S_ID          SUBJECT          MARK
1             English          90
1             Math             40
1             Computer         30
2             English          85
2             Math             10
2             Computer         06
3             English          10
3             Math             20
3             Computer         40

To this form

S_ID       English        Math         Computer
1          90             40           30
2          85             10           06
3          10             20           40

using SQL code,

I'm using MS Access 2010,

Thank you

SELECT S_ID ,
       MAX(CASE WHEN subject = 'English' THEN mark ELSE null END) AS English,
       MAX(CASE WHEN subject = 'Math' THEN mark ELSE null END) AS Math,
       MAX(CASE WHEN subject = 'Computer' THEN mark ELSE null END) AS Computer
FROM myTable
GROUP BY S_ID 

You want a cross-tab query which will yield a column per subject;

TRANSFORM Sum(MARK) AS TotalMark
SELECT 
   S_ID
FROM marks
   GROUP BY S_ID
PIVOT SUBJECT;

if this is a one time exercise, you could use many statements, sequentially: something like this:

insert into new_table
select distinct s_id, 0,0,0
from old_table

then a series of updates

update new_table n
set english = (select english from old_table where s_id = n.s_id )
where s_id = n.s_id

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