数据库 - Perl脚本的SQL表

时间:2012-10-03 06:19:32

标签: perl

我在SQL中创建了一个'transaction'表,如下所示:

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;

我哪里错了?

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:0)

使用SQL获取此答案而非代码。

SELECT AccountNumber, Type, SUM(Amount) FROM transaction GROUP BY AccountNumber, Type;