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
之上使用,我在cate_name
(THX Gordon Linoff)添加了2个字段final_price
和ideal_result_table
现在我想在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
答案 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
CMIIW
EDITED ..