作者TeemingVoid (TeemingVoid)
看板Database
标题Re: [SQL ] php中加总的一些问题
时间Tue Aug 21 20:06:47 2012
※ 引述《raindays035 (等待 是一种过程)》之铭言:
: 在php提取资料库资料中遇到一些问题
: 大致上资料表如下:
: ID 帐号 活动 余额
: 1 abc A 10000
: 2 abc A 3000
: 3 abc A 2000
: 4 def A 4000
: 5 def A 1000
: 6 def A 2000
: 7 abc B 4000
: 8 def B 2000
: 现在想要取得活动A中 各个帐户的最後余额总额
: 即 ID = 3,ID = 6 的余额:2000 + 2000 = 4000
推 ShangTang:用一个变数判别帐户,然後每个帐户都用阵列的一个位置如 08/21 18:52
→ ShangTang:何? 08/21 18:53
→ raindays035:感谢楼上 我想到方法了 我在while前面放一个$i=0 08/21 19:08
→ raindays035:while里面放$i=$i+$ans[0] 最後印出$i就可以了 08/21 19:10
很开心解决了! :-)
谨提供一个比较偏资料库的作法:
(以 MySQL + PHP 举例)
use test;
create table lab (id int, account varchar(10), action varchar(3), balance
int);
insert into lab values
(1, 'abc', 'A', 10000),
(2, 'abc', 'A', 3000),
(3, 'abc', 'A', 2000),
(4, 'def', 'A', 4000),
(5, 'def', 'A', 1000),
(6, 'def', 'A', 2000),
(7, 'abc', 'B', 4000),
(8, 'def', 'B', 2000);
於是,您的 PHP 程式就类似这样:
<?php
$action = "A";
$con = mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_selectdb("test", $con);
$command = <<<MultiLines
select sum(balance) as total
from lab as t
where id = (select max(id)
from lab where account = t.account and action = '$action');
MultiLines;
$result = mysql_query($command);
$row = mysql_fetch_array($result);
printf("Total: %s", $row["total"]);
mysql_free_result($result);
mysql_close($con);
?>
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.38.81.113
1F:推 raindays035:感谢T大,抱歉现在才看到 = = 09/01 15:21