如何在SQL中使用sum函数比较列值?

时间:2018-10-17 07:07:34

标签: php mysql sql

我有三个表:

  1. mls_category
  2. points_martix
  3. mls_entry

我的第一个表(mls_category)如下:

*--------------------------------*
| cat_no |  store_id | cat_value |
*--------------------------------*
|   10   |    101    |     1     |
|   11   |    101    |     4     |
*--------------------------------*

我的第二张表(points_martix)如下:

*----------------------------------------------------*
| pm_no |  store_id | value_per_point | max_distance |
*----------------------------------------------------*
|   1   |    101    |       1         |      10      |
|   2   |    101    |       2         |      50      |
|   3   |    101    |       3         |      80      |
*----------------------------------------------------*

我的第三张表(mls_entry)如下:

*-------------------------------------------*
| user_id |  category | distance |  status  |
*-------------------------------------------*
|    1    |     10    |    20    | approved |
|    1    |     10    |    30    | approved |
|    1    |     11    |    40    | approved |
*-------------------------------------------*

我正在使用以下查询来显示某些条件下的距离总和:

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

这使我求和 60 为total_distance,这是我想要的正确值。

现在,我想包含第三张表(points_matrix),并想比较我的sum(60)小于或等于80(最大距离),那么我的新值将是60*3=180

因此,假设我的总和是 10 ,那么我的新值将是10*1=10,如果我的总和是 25 ,那么我的新值将是根据点矩阵25*2=50

2 个答案:

答案 0 :(得分:2)

Yon可以使用MIN()来计算所需的value_per_point,整个sql如下:

SELECT MIN(b.value_per_point) * d.total_distance FROM points_matrix b 
JOIN 
(
    SELECT store_id, 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
) d ON b.store_id = d.store_id AND b.max_distance >= d.total_distance

答案 1 :(得分:0)

使用Correlated Subquery

SELECT 
  dt.total_distance * dt.max_points 
FROM (
      SELECT SUM(t1.totald/c.cat_value) AS total_distance, 
             (
              SELECT value_per_point 
              FROM points_martix 
              WHERE SUM(t1.totald/c.cat_value) >= max_distance
              ORDER BY max_distance ASC LIMIT 1
             ) AS max_points 
      FROM mls_category AS c 
      JOIN (
            SELECT SUM(distance) AS totald, 
                   user_id, 
                   category 
            FROM mls_entry 
            WHERE user_id= 1 AND 
                  status = 'approved' 
            GROUP BY user_id, category
           ) AS t1 on c.cat_no = t1.category
    ) AS dt