Complex Join - involving date ranges and sum...

Posted by calumbrodie on Stack Overflow See other posts from Stack Overflow or by calumbrodie
Published on 2010-05-03T15:48:36Z Indexed on 2010/05/03 15:58 UTC
Read the original article Hit count: 308

Filed under:
|
|
|

I have two tables that I need to join... I want to join table1 and table2 on 'id' - however in table two id is not unique. I only want one value returned for table two, and this value represents the sum of a column called 'total_sold' - within a specified date range (say one month)..

SELECT ta.id, tb.total_sold as total_sold_this_week
FROM table_a as ta
LEFT JOIN table_b as tb ON ta.id=tb.id AND tb.date_sold BETWEEN ADDDATE(NOW(),INTERVAL -3 WEEK) AND NOW()

this works but does not SUM the rows - only returning one row for each id... how do I get the sum from table b instead of only one row??? Please criticise if format of question could use more work - I can rewrite and provide sample data if required - this is a trivialised version of a much larger problem.

-Thanks

© Stack Overflow or respective owner

Related posts about mysql

Related posts about join