 |
สอบถามการ query ที่ถูกวิธีค่ะ รู้สึกว่า น่าจะมีวิธีที่ดีกว่าที่หนูใช้อยู่ค่ะ |
|
 |
|
|
 |
 |
|
ลองใช้วิธีเก็บค่า total ใส่ไว้ในตัวแปร array น่ะครับ
ทั้งหมด 12 ค่า ใน array คือ 0-11
*** ผมยังไม่ค่อยเข้าใจว่าคุณจะหาอะไรน่ะครับ
อาจไม่ตรงความต้องการเท่าไหร่ เพราะดูโค้ดคุณแล้ว น่าจะมีการวนลูปค่า id อีกหลายตัว และแต่ละ id ก็ต้องเก็บ totalทั้ง 12 เดือนอีก
อันนี้เป็น Code ตัวอย่างที่ผมทำขึ้นมาง่ายๆ เอาไปรันดูเป็นแนวทางน่ะครับCode (PHP)
<?
$S_month = 1;
$Month = 12;
while($Month > 0)
{
$total[]=$S_month;
$S_month++;
$Month = $Month -1;
}
$size=Count($total);
$array_st=0;
while($size > 0)
{
echo $total[$array_st]."<br>";
$array_st++;
$size = $size-1;
}
?>
|
ประวัติการแก้ไข 2011-06-08 18:40:11 2011-06-08 18:40:26
 |
 |
 |
 |
Date :
2011-06-08 18:39:47 |
By :
mangkunzo |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
SELECT
sumif(MONTH(docudate)='01', total, 0) as total01
sumif(MONTH(docudate)='02', total, 0) as total02
sumif(MONTH(docudate)='03', total, 0) as total03
.........
sumif(MONTH(docudate)='12', total, 0) as total12
FROM tb_total
WHERE id_product=$id_product AND YEAR(docudate) = '$year' ";
ใส่พวกเครื่องหมาย '' หรือ "" ให้ถูกด้วยนะครับ แล้วก็เอา query ไปลองใน Tool ต่างๆเพื่อความชัวร์ด้วยนะครับ
|
 |
 |
 |
 |
Date :
2011-06-08 18:50:58 |
By :
Songkram |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ใส่ index ให้กับฟิลด์ id_product , docudate ลองดูว่ามันเร็วขึ้นไหม
|
 |
 |
 |
 |
Date :
2011-06-08 20:07:43 |
By :
avsqlz |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|

|
 |
 |
 |
 |
Date :
2011-06-08 21:08:26 |
By :
g4est |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
sum if ใช้กับ mysql ได้อย่างเดียวใช่ไหมคะ พอใช้กับ mssql แล้วจะ error ค่ะ
|
ประวัติการแก้ไข 2011-06-08 22:30:22 2011-06-08 22:45:46 2011-06-08 23:13:51
 |
 |
 |
 |
Date :
2011-06-08 22:29:52 |
By :
naked13 |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
$sql="select tb_product.id_product,MONTH(tb_total.docudate) as month_num,sum(tb_total.total) as totalx from tb_product
inner join tb_total on tb_product.id_product=tb_total.id_product
where tb_product.name_product like '%milk%' and AND YEAR(tb_total.docudate) = '$year'";
group by tb_product.id_product,MONTH(tb_total.docudate)
order by 1,2";
$query=mssql_db_query($sql);
while($result=mssql_fetch_array($query)){
$total_all_id_produce_12month[$result[id_product]][intval($result[month_num])]=$result[totalx];
}
ตอนเอาไปใช้ก็
foreach($total_all_id_produce_12month as $id_product=>$arr_total){
for($i=1;$i<=12;$i++){
echo"<br>$id_product ==> month($i)==> ".$arr_total[$i];
}
}
ก็ประมาณนี้ (เอาไป run แล้วอาจมี error บ้างเพราะเขียนสด ไม่ได้ test ครับ)
ปล.ถ้าข้อมูลจำนวนมาก INDEX จะมีผลอย่างเห็นได้ชัด
|
 |
 |
 |
 |
Date :
2011-06-09 02:44:24 |
By :
ผ่านมา |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|