Question

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

Used above coding CASE and JOIN, I added 2 fields cate_name and final_price at ideal_result_table (THX Gordon Linoff)

Now I would like to calculate 2 more fields called avg_rate and count_comment at ideal_result_table, how can I do that?

User AAA and BBB added rating to the book 001, so avg_rateof book 001 is (4+5)/2 = 4.5 = 5

User CCC added rating to the book 002, so avg_rate of book 002 is 2

User XXX and YYY added comment to the book 001, so count_comment of book 001 = 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
Was it helpful?

Solution

try this :

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..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top