 |
สอบถาม การดึงข้อมูลในฐานข้อมูลมาหาผลรวมมีแบบมีเงื่อนไข ค่ะ |
|
 |
|
|
 |
 |
|
แบบนี้น่าจะได้นะ ลองเอาไปลองดูครับ
Code (SQL)
SELECT
A.id_student
,A.sum1_5
,B.sum6_10
FROM
(
SELECT
id_student
,sum(score)as sum1_5
FROM tb_answer
WHERE id_question BETWEEN '1' and '5'
GROUP BY
id_student
) A
LEFT OUTER JOIN(
SELECT
id_question
,sum(score)as sum6_10
FROM tb_answer
WHERE id_question BETWEEN '6' and '10'
GROUP BY
id_student
) B ON A.id_student = B.id_question
|
 |
 |
 |
 |
Date :
2017-04-11 07:09:50 |
By :
thesin18598 |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ขอบคุณ thesin18598 สำหรับ code SQL ค่ะ
นำมาทดลองใช้แล้ว สามารถแสดงผลรวมข้อที่ 1-5 แต่ไม่แสดงผลรวมข้อที่ 6-10 จะต้องปรับแก้ไขส่วนไหนเพิ่มเติมได้บ้างค่ะ
อันนี้เป็น code ที่นำไปประยุกต์ใช้ค่ะ
Code (PHP)
<?
include("config.php");
$strSQL= "SELECT A.id_student , A.sum1_5 , B.sum6_10
FROM (SELECT id_student ,sum(score) as sum1_5 FROM tb_answer
WHERE id_question BETWEEN '1' and '5' GROUP BY id_student)
A LEFT OUTER JOIN (SELECT id_question ,sum(score)as sum6_10
FROM tb_answer WHERE id_question BETWEEN '6'and '10'
GROUP BY id_student) B ON A.id_student = B.id_question";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
while($row = mysql_fetch_array($objQuery)){
?>
<table>
<tr>
<td>
รหัสนักเรียน <?=$row['id_student']?>
คะแนนรวม ข้อที่ 1-5 = <?= $row['sum1_5']; ?> คะแนน
</td>
<td>
รหัสนักเรียน <?=$row['id_student']?>
คะแนนรวม ข้อที่ 6-10 = <?= $row['sum6_10']; ?> คะแนน
</td></tr>
<?}?>
</table>

|
ประวัติการแก้ไข 2017-04-13 00:38:57 2017-04-13 00:40:03
 |
 |
 |
 |
Date :
2017-04-13 00:36:41 |
By :
ta_ta |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ลองเปลี่ยน query ดูครับ
Code (PHP)
select id_student,group_question,sumscore from
(
select id_student,sum(score) as sumscore,'1-5' as group_question from tb_answer where id_question between 1 and 5 group by id_student
union
select id_student,sum(score) as sumscore,'6-10' as group_question from tb_answer where id_question between 6 and 10 group by id_student
) as a order by id_student,group_question
|
 |
 |
 |
 |
Date :
2017-09-25 15:32:25 |
By :
Mr.X |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ถ้าที่ละ 5 ข้อ ใช้ ceiling หาร 5
Code (SQL)
SELECT
ceil( id / 5) * 5 - 4 as st,
ceil( id / 5) * 5 as en,
sum(score) as s
FROM `tbname`
group by ceil(id / 5)
|
 |
 |
 |
 |
Date :
2017-09-25 19:27:05 |
By :
Chaidhanan |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|