我的数据库:
+++++++++++++++++++++++++++++++++++++
+ id | group_id | inside_id | value +
+ 1 | 1 | 1 | 50 +
+ 2 | 1 | 2 | 12 +
+ 3 | 1 | 1 | 4 +
+ 4 | 2 | 3 | 140 +
+ 5 | 2 | 2 | 81 +
+ 6 | 2 | 3 | 24 +
+++++++++++++++++++++++++++++++++++++
我想做这样的事情:
SELECT
group_id,
SUM(CASE WHEN MAX(inside_id) = inside_id THEN value ELSE 0 END) as sum_value
FROM table
GROUP BY group_id
预期结果:
++++++++++++++++++++++++
+ group_id | sum_value +
+ 1 | 12 +
+ 2 | 164 +
++++++++++++++++++++++++
我在左连接中使用此查询,这是我之前不知道的原因,inside_id
包含的值{我只需要inside_id
最大值时的总和在当前组中,问题是组功能内的组功能不起作用导致"无效使用组功能"。
inside_id
group_id
只包含两种可能性。
答案 0 :(得分:1)
尝试这样的事情
SELECT group_id, SUM(value) as sum_value
FROM table A
Where inside_id = (select max(inside_id) from table B where a.group_id=b.group_id)
GROUP BY group_id
sub-query
会找到每个inside_id
group_id
使用correlated sub-query
和conditional aggregate
的另一种方法,与您当前的尝试类似。
SELECT group_id,
Sum(CASE
WHEN inside_id = (SELECT Max(inside_id)
FROM table B
WHERE a.group_id = b.group_id) THEN value
ELSE 0
END) AS sum_value
FROM table A
GROUP BY group_id
答案 1 :(得分:1)
这是一个选项,它使用带有不相关子查询的连接来识别,然后求和每个组最大inside_id
的记录。
SELECT t1.group_id, SUM(t1.value) AS sum_value
FROM yourTable t1
INNER JOIN
(
SELECT group_id, MAX(inside_id) AS inside_id
FROM yourTable
GROUP BY group_id
) t2
ON t1.group_id = t2.group_id AND
t1.inside_id = t2.inside_id
GROUP BY t1.group_id
答案 2 :(得分:0)
SELECT group_id,SUM(value) as sum_value
FROM table
WHERE group_id<>inside_id
GROUP BY group_id