title: How to compare columns values with sum function in SQL?
body: <p>I have three tables :</p>
  
  <ol>
  <li>mls_category</li>
  <li>points_martix</li>
  <li>mls_entry</li>
  </ol>
  
  <p>My first table (mls_category) is like below:</p>
  
  <pre><code>*--------------------------------*
  | cat_no |  store_id | cat_value |
  *--------------------------------*
  |   10   |    101    |     1     |
  |   11   |    101    |     4     |
  *--------------------------------*
  </code></pre>
  
  <p>My second table (points_martix) is like below:</p>
  
  <pre><code>*----------------------------------------------------*
  | pm_no |  store_id | value_per_point | max_distance |
  *----------------------------------------------------*
  |   1   |    101    |       1         |      10      |
  |   2   |    101    |       2         |      50      |
  |   3   |    101    |       3         |      80      |
  *----------------------------------------------------*
  </code></pre>
  
  <p>My third table (mls_entry) is like below:</p>
  
  <pre><code>*-------------------------------------------*
  | user_id |  category | distance |  status  |
  *-------------------------------------------*
  |    1    |     10    |    20    | approved |
  |    1    |     10    |    30    | approved |
  |    1    |     11    |    40    | approved |
  *-------------------------------------------*
  </code></pre>
  
  <p>I am using the following query to show the sum of  distance with some condition:</p>
  
  <pre><code>SELECT SUM(t1.totald/c.cat_value)
  AS total_distance 
  FROM mls_category c 
  JOIN 
      (SELECT SUM(distance) totald, user_id, category 
       FROM mls_entry 
       WHERE user_id = 1
       AND status = 'approved' 
       GROUP BY user_id, category) t1 
  ON c.cat_no = t1.category
  </code></pre>
  
  <p>This gives me sum <strong>60</strong> as total_distance, that is correct which I wanted.</p>
  
  <p>Now, I want to include the third table (points_matrix) and want to compare my <code>sum(60)</code> is less than or equal to 80(max_distance) then my new value would be <code>60*3=180</code>.</p>
  
  <p>So, suppose my sum comes <strong>10</strong> then my new value will be <code>10*1=10</code> and if my sum comes <strong>25</strong> then my new value will be according to point matrix <code>25*2=50</code>.</p>