 |
แนะนำ Mysql หน่อยครับ อยากหาจำนวน ของ Motorcycle ของแต่ล่ะ Todohukencode อ่ะครับ ถ้ามีค่าว่าง ให้เป็น 0 ครับ |
|
 |
|
|
 |
 |
|
โจทย์ครับ : The number of motorcycles following each matched todouhuken (if it is null, it will be showed 0).
Query ของผมครับ
select t.todouhuken_code,
t.todouhuken_name,
t.todouhuken_area_code2,
area_name,
count(case when motorcycle_no is null then 0 else motorcycle_no end) as cnt
from mst_area a left join
mst_todouhuken t
on (a.area_code2 = t.todouhuken_area_code2) and (a.area_code = t.todouhuken_area_code) left join
search_motorcycle s
on t.todouhuken_code = s.dealer_todouhuken_code left join
mst_model_v2 v2
on (s.motorcycle_model_code = v2.model_code) and (s.motorcycle_maker_code = v2.model_maker_code)
where motorcycle_jyoukyo in (1,5,6) and
model_maker_code = 4 and
dealer_todouhuken_code > 0
group by todouhuken_code,todouhuken_area_code2,todouhuken_name,todouhuken_name,area_name asc
order by todouhuken_area_code2,todouhuken_code asc
ผลลัพท์ครับ

รบกวนด้วยนะครับ
Tag : PHP, MySQL
|
|
 |
 |
 |
 |
Date :
2017-10-06 09:28:14 |
By :
sangwondee |
View :
614 |
Reply :
4 |
|
 |
 |
 |
 |
|
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
count(case when motorcycle_no is null then 0 else motorcycle_no end) as cnt
ถ้าต้องการแค่ count
count(motorcycle) แค่นี้พอ เพราะไม่ว่า motorcycle จะมีค่าเท่าไหร่ จะนับเป็น 1 ถ้าไม่ใช่ null
แต่ถ้าต้องการ บวก motorcycle ทั้งหมดตามค่าของ motorcycle
sum(coalesce(motorcycle_no,0)) as cnt ถ้า motorcycle มีค่าเป็น null จะเปลี่ยนเป็น 0 ให้
|
 |
 |
 |
 |
Date :
2017-10-06 09:53:51 |
By :
Chaidhanan |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ได้ค่าเหมือนเดิม ครับ

ผลที่อยากให้ได้มันเป็น 0 ครับ
หรือผมเชื่อมตารางผิดหรือป่่าวครับ
|
ประวัติการแก้ไข 2017-10-06 10:20:20
 |
 |
 |
 |
Date :
2017-10-06 10:08:26 |
By :
sangwondee |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Code (SQL)
SUM(IF(motorcycle_no = null,0, 1)) as cnt
|
 |
 |
 |
 |
Date :
2017-10-06 11:52:26 |
By :
Krungsri |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ยังเหมือนเดิมเลยครับ
แต่ได้คำแนะนำเพิ่มเติมครับ
1. Your result don't have cnt = 0 because of your query can't count when todouhuken_code has cnt = 0
2. With motorcycle_maker_code = 4, only have todouhuken_code=1,3,4,....
Using this query to check:
----------------
SELECT
*
FROM
webikept.search_motorcycle
WHERE
motorcycle_maker_code = 4
GROUP BY dealer_todouhuken_code;
-----------------
So if you use t.todouhuken_code = s.dealer_todouhuken_code
AND model_maker_code = 4 in WHERE, it will make data lost
|
 |
 |
 |
 |
Date :
2017-10-06 12:18:02 |
By :
sangwondee |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|