【问题标题】:SQL Join Tables, Aggregate Column within RangeSQL 连接表,聚合范围内的列
【发布时间】:2015-07-22 12:58:51
【问题描述】:

我的数据库中有两个表,如下所示:

 event  | id | value
--------------------
   1    | A  |   10
   2    | B  |   10
   3    | C  |   15
   4    | A  |   15
   5    | D  |   20
   6    | B  |   25

id | value | cost
-----------------
 A |   11  |  5
 B |   12  |  5
 A |   13  |  5
 A |   14  |  5
 C |   16  |  5
 D |   35  |  5

如果 t2 中的 value 列在一定范围内,我想对表 1 中的 eventid 列进行分组,然后对表 2 中的 cost 列求和,以获得相应的 id t1 中的value 列。

例如,如果我的范围是 +3,我想返回:

id_event | total
----------------
   A1    |  10    // 2 rows in t2 with id=A and value between 10 and 13, each with cost = 5
   B2    |  5  
   C3    |  5  
   A4    |  0     // For A4, t1 value = 15, no (id=A) entries in t2 with 15 < value <= 18
   D5    |  0  
   B6    |  0  

我还不能完成这项工作......任何提示都非常感谢!我最熟悉MySQL。最终我将不得不在 MS Access 中实现这一点,但最好知道如何在两者中实现它。谢谢!


编辑:这是我正在尝试的代码。它仅适用于在第二个表中仅出现一次的那些 ID。

SELECT t1.id || t1.event as id_ev, 
       (SELECT SUM(t2.cost) WHERE t2.value <= (t1.value +3) 
                                  AND (t2.value >= t1.value)) as total_cost
FROM ind_e LEFT JOIN data
ON t1.id = t2.id
GROUP BY t1.id || t2.event;

【问题讨论】:

    标签: mysql sql ms-access


    【解决方案1】:

    您可以通过在此聚合求和函数中使用条件 case 表达式来获得所需的结果。

    使用 MySQL(或任何符合 ANSI SQL 的数据库),查询可能如下所示:

    select 
        concat(t1.event, t1.id) id_event, 
        sum(case when t2.value between t1.value and t1.value + 3 then t2.cost else 0 end) total
    from table1 t1
    inner join table2 t2 on t1.id = t2.id
    group by concat(t1.event, t1.id)
    

    concat 应更改为与您正在使用的特定数据库一起使用的字符串连接函数。

    MS Access 使用稍微不同的语法,我认为它应该是这样的:

    select 
        t1.event & Cstr(t1.id) id_event, 
        sum(iif(t2.value between t1.value and t1.value + 3, t2.cost,0)) total
    from table1 t1
    inner join table2 t2 on t1.id = t2.id
    group by t1.event & Cstr(t1.id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2014-11-18
      • 2012-09-18
      • 2023-03-06
      • 2014-12-16
      相关资源
      最近更新 更多