[英]How to use CASE plus JOIN plus GROUP BY into a single MySQL statement
SELECT B. * , SC.cate_name, (
CASE WHEN special_offer_type = 'Fixed Value'
THEN B.price - special_offer
WHEN special_offer_type = 'Discount %'
THEN B.price * ( 1 - special_offer / 100.0 )
ELSE B.price
END
) AS final_price
FROM book B
JOIN setting_category SC ON B.cate_id = SC.cate_id
在上面的編碼CASE
和JOIN
,我在ideal_result_table
(THX Gordon Linoff)處添加了兩個字段cate_name
和final_price
現在,我想在ideal_result_table
處再計算2個稱為avg_rate
和count_comment
的ideal_result_table
,我該怎么做?
用戶AAA和BBB向圖書001添加了評分,因此圖書001的avg_rate
為(4 + 5)/ 2 = 4.5 = 5
用戶CCC向書002添加了評分,因此書002的avg_rate
為2
用戶XXX和YYY向書001添加了注釋,因此書001的count_comment
= 2
book
-----------------------------------------------------------
isbn cate_id price special_offer special_offer_type
001 1 125 5 Fixed Value
002 1 90 30 Discount %
003 2 150 50 Fixed Value
setting_category
--------------------
cate_id cate_name
1 Fiction
2 Dictionary
book_rating
------------------------------------------
user dateadd timeadd isbn rate
AAA 2014/03/20 15:00:00 001 4
BBB 2014/03/21 15:00:00 001 5
CCC 2014/03/22 15:00:00 002 2
book_comment
----------------------------------------------
user dateadd timeadd isbn comment
XXX 2014/03/20 16:00:00 001 good
YYY 2014/03/21 16:00:00 001 great
ideal_result_table
-----------------------------------------------------------------------------------------------------------------
isbn cate_id price special_offer special_offer_type cate_name final_price avg_rate count_comment
001 1 125 5 Fixed Value Fiction 120 5 2
002 1 90 30 Discount % Fiction 63 2 0
003 2 150 50 Fixed Value Dictionary 100 0 0
嘗試這個 :
SELECT B.*,SC.cate_name,( CASE WHEN special_offer_type ='Fixed Value' THEN B.price - special_offer WHEN special_offer_type = 'Discount %' THEN B.price * ( 1 - special_offer / 100.0 ) ELSE B.price END ) AS final_price, IFNULL(xx.avg_rate,'0'), IFNULL(yy.count_comment,'0') FROM book B JOIN setting_category SC ON B.cate_id = SC.cate_id LEFT JOIN (select a.isbn,sum(a.rate)/count(a.rate) as avg_rate from book_rating a group by a.isbn) as xx on b.isbn = xx.isbn LEFT JOIN (select c.isbn,count(*) as count_comment from book_comment c group by c.isbn) as yy on b.isbn = yy.isbn
II
編輯..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.