0

数据库:mysql>ver 5.0

table 1: type_id (int), type
table 2: name_id, name, is_same_as = table2.name_id or NULL
table 3: id, table2.name_id, table1.type_id, value (float)

我想对值求和,并计算table 3where中的值table2.name_id是相同的,并且还包括idwhere的值is_same_is=name_id。我想为 中table3的所有值选择所有数据table2

如果我的问题不是很清楚,并且已经回答但我无法找到相关答案,请道歉。或者不完全知道要寻找什么。

[data]. table1
id | type
=========
1  | test1
2  | test2

[data].table2
name_id  |  name  | is_same_as
==============================
1        |  tb_1  | NULL
2        |  tb_2  | 1
3        |  tb_3  | NULL
4        |  tb_4  | 1

[data].table3
id    |   name_id  |  type_id | value
======================================
1     |   1        |  1       | 1.5
2     |   2        |  1       | 0.5
3     |   2        |  2       | 1.0


output:
name_id| type_id|SUM(value)
=======================================================
1      | 1      |2.0  < because in table2, is_same_as = 1
2      | 2      |1.0
4

2 回答 2

0

我认为以下内容可以满足您的要求:

select coalesce(t2.is_same_as, t2.name_id) as name_id, t3.type_id, sum(value)
from table_3 t3 join
     table_2 t2
     on t3.name_id = t2.name_id
group by coalesce(t2.is_same_as, t2.name_id), t3.type_id
order by 1, 2

它在 上加入表name_id。但是,它会使用该is_same_as列(如果存在或name_id不存在)来汇总数据。

于 2012-10-05T21:28:21.653 回答
0

这可能是你要找的:(我没有在 MySQL 中测试过,所以可能有错字)

with combined_names_tab (name_id, name_id_ref) as
(
select name_id, name_id from table2
union select t2a.name_id, t2b.name_id
  from table2 t2a 
  join table2 t2b 
    on (t2a.name_id = t2b.is_same_as)
)
select cnt.name_id, t3.type_id, sum(t3.value) sum_val
  from combined_names_tab cnt
  join table3 t3
    on ( cnt.name_id_ref = t3.name_id )
 group by cnt.name_id, t3.type_id
having sum(t3.value) / count(t3.value) >= 3

以下是查询的作用:

首先,它创建“combined_names_tab”,它是您希望使用“is_same_as”列进行分组的所有 table2 行的连接来做出决定。我确保通过执行 UNION 来包含“父”行。

其次,一旦你有了上面的那些行,它就是一个简单的连接到 table3 的一个 GROUP BY 和一个 SUM。

注意: table1 是不必要的(我相信)。

让我知道这个是否奏效!

约翰...

于 2012-10-05T21:30:29.650 回答