所以这是表格:
Name Indicator Amount
Anson 1,2 6.1
Anson 4,5 11.6
Ben 1 7
Ben 3,4 8.3
如果指标连续,我怎样才能获得总金额? 这是我想要的结果:
{{1}}
谢谢!
答案 0 :(得分:1)
不幸的是,MySQL没有窗口功能。但是,如果您有一系列值递增1,那么该序列与Indicator
之间的差异对于每个组都是不变的。您可以使用变量创建这样的序列。
其余的只是算术和聚合:
select name, group_concat(indicator), sum(amount)
from (select t.*, (@rn := @rn + 1) as rn
from table t cross join
(select @rn := 0) params
order by name, indicator
) t
group by name, (rn - indicator)
order by name, min(indicator);
答案 1 :(得分:0)
试试这个,它适用于Oracle,所以我认为它应该在mysql中。它不漂亮......使用滞后功能来显示以前名称的指标和金额。然后找出指标之间的差异并总结金额。最后使用CASE语句格式化返回的结果。
select name,
CASE diff WHEN 1 THEN to_char(prev_ind||','||indicator)
ELSE to_char(indicator) END as Indicator,
CASE diff WHEN 1 then to_char(sum_amount)
else to_char(amounnt) END as Amount
FROM (
select name, indicator, prev_ind, sum(indicator-prev_ind) as diff, amounnt,
sum(amounnt + prev_amount) sum_amount
from (
select name, indicator, lag(indicator,1,0) over (order by name) prev_ind, amounnt,
lag(amounnt,1,0) over (order by name) prev_amount
from tmp1
order by name, indicator
)
group by name, indicator, prev_ind, amounnt
order by name, indicator)
where diff != 2
order by name;