作者diamondking (迷惘)
看板Database
标题Re: [SQL ] 询问一个 SQL 语法
时间Sat May 17 12:46:39 2008
※ 引述《statue (statue)》之铭言:
: 我有一张表格, 表格内容大概如下
: source type dest count
: B damage A 1000
: C heal A 800
: D heal A 600 (溢捕 400)
: E damage C 400
: D heal C 600 (溢捕 200)
: damage 表示伤害, heal 表示治疗
: 如果我想用 SQL 知道 D 的溢捕量, 可以用 SQL 求得吗?
一些前提如下:
1、战斗纪录应该是有时间顺序的,所以假设顺序由上到下先後发生。
2、我记得艾大用的是mysql? 先假设是好了。
3、新增一个「num」的流水号栏位,表时间性。
4、type和count为mysql关键字,先假设改为type1、count1
5、假设Table Name是test1
求得所有人溢补量之SQL如下:
select c.source, greatest(sum(c.heal)-sum(c.damage), 0) overheal from
(
select a.source, a.num, max(a.count1) heal,
greatest
(
sum(case when b.type1='damage' then b.count1 else b.count1*-1 end), 0
) damage
from test1 a, test1 b
where a.dest=b.dest and b.num<a.num and a.type1='heal'
group by a.num, a.source
) c group by c.source
执行完,可得结果:
source overheal
C 0
D 600
简单说明一下:
内层的子查询,是自己join自己,设法找出较早发生的damage和heal来计算之,
外层则针对source来group。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.166.129.119
※ 编辑: diamondking 来自: 118.166.129.119 (05/17 12:53)