-1

可能重复:
从 Perl 中的数据库到电子表格

我有一个这样的事务表:

TranID  Date        AccNum   Type    Amount ChequeNo DDNo  
657520  02-07-1999  0181432  Debit   16000  465774     
657524  02-07-1999  0181432  Debit   13000           569086
657538  09-07-1999  0181432  Credit  11000  
657548  18-07-1999  0181432  Credit  15500  
657519  02-07-1999  0181432  Debit   12000  
657523  02-07-1999  0181432  Credit  11000  
657529  03-07-1999  0181433  Debit   15000  466777
657539  10-07-1999  0181433  Credit  10000  
657541  11-07-1999  0181433  Debit   12000  
657525  03-07-1999  0181433  Debit   15000           569999
657533  05-07-1999  0181433  Credit  12500  

我的问题是:从交易表中查询数据并计算每个账户的支票、dd和现金借记的总金额。我的代码是这样的:

#!/usr/bin/perl
use strict;
use warnings;
use DBI; 

print "content-type:text/html\n\n";

my $dbh = DBI->connect('dbi:mysql:database:3306','prithvi','prithvi') 
    or die "Couldn't connect";

my $tran_cur = $dbh->prepare("SQL Query");
$tran_cur->execute;

map { print "<td>$_</td>" } qw(AccountNumber-ChequeDebit-DDDebit-CashDebit);
print "<br/>";

while (my @data = $tran_cur->fetchrow_array()) {

    my $rec = join '-', @data;
    print "$rec<br/>";
}
$tran_cur->finish;
$dbh->disconnect;

谁能告诉我如何使用单 SQL 查询来解决这个问题:我希望输出为:

AccountNumber-ChequeDebit-DDDebit-CashDebit
0181432-16000-13000-12000
0181433-15000-15000-12000

提前致谢。请帮忙。

4

1 回答 1

1

试试下面的代码:

#!/usr/bin/perl
use strict;
use warnings;
use DBI;

print "content-type:text/html\n\n";

my $dbh = DBI->connect('dbi:mysql:database:3306','prithvi','prithvi')
    or die "Couldn't connect";

my $tran_cur = $dbh->prepare("
    SELECT `AccNum`, `Amount`
    FROM `database`
    WHERE `Type` = 'Debit'
    ORDER BY `TranID`;
");
$tran_cur->execute;

print "<br>AccountNumber-ChequeDebit-DDDebit-CashDebit</br>\n";

my %h;

while (my @data = $tran_cur->fetchrow_array()) {
    if ($h{$data[0]}) {
        $h{$data[0]} .= "-$data[1]";
    }
    else {
        $h{$data[0]} = $data[1];
    }
}

$tran_cur->finish;
$dbh->disconnect;

foreach my $key (sort keys(%h)) {
    print "<td>$key" . "-" . $h{$key} . "</td>\n";
}

它是完美的,但它有效;)

于 2012-10-07T17:24:02.617 回答