-1

我在 SQL 中创建了一个“事务”表,如下所示:

TransactionID    Date           AccountNumber   Type    Amount  
657520           02-07-1999     016901581432    Debit   16000  
657524           02-07-1999     016901581432    Debit   13000  
657538           09-07-1999     016901581432    Credit  11000  
657548           18-07-1999     016901581432    Credit  15500  
657519           02-07-1999     016901581433    Debit   12000  
657523           02-07-1999     016901581433    Credit  11000  
657529           03-07-1999     016901581433    Debit   15000  
657539           10-07-1999     016901581433    Credit  10000  
657541           11-07-1999     016901581434    Debit   12000  
657525           03-07-1999     016901581434    Debit   15000  
657533           05-07-1999     016901581434    Credit  12500  

我必须使用数据库找到每个帐户的总借方金额和总贷方金额。我的代码是这样的:

#!/usr/bin/perl
use DBI;
use strict;
use warnings;
print "content-type:text/html\n\n";
$dbh = DBI->connect('dbi:___','prithvi','*password*') or die "Couldn't connect";
my %trans;
my $tran = $dbh->prepare("SELECT * FROM `transaction` LIMIT 0 , 11");
$tran->execute;
while(my @row = $tran->fetchrow_hash) 
{
    my $tran = join ',', @row;
    $trans{$tran[2]}{$tran[3]} += $tran[4];
}
foreach my $acno(sort keys %trans) 
{
print "Total Amount deposited and total amount credited for Account Number $acno is Rs.$trans{$acno}{'Debit'} and Rs.$trans{$acno}{'Credit'}\n";
}
$tran->finish;
$dbh->disconnect;

我哪里错了?

4

2 回答 2

1

如果你添加use strictuse warnings你可能会得到一些关于需要在下面的代码中声明 @tran 的反馈:

while(my @row = $tran->fetchrow_hash) 
{
    my $tran = join ',', @row;
    $trans{$tran[2]}{$tran[3]} += $tran[4];
}

$tran 是657520,02-07-1999,016901581432,Debit,16000当您尝试将其用作数组时。

最后使用 Data::Dumper 显示您放入 %trans 的内容:

use Data::Dumper;
print Dumper(\%trans);

你的意思是:

while(my @row = $tran->fetchrow_array) 
{
    $trans{$row[2]}{$row[3]} += $row[4];
}
于 2012-10-03T07:53:41.653 回答
0

使用 SQL 得到这个答案而不是代码。

SELECT AccountNumber, Type, SUM(Amount) FROM transaction GROUP BY AccountNumber, Type;
于 2012-10-03T07:12:32.373 回答