0

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

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; 
use Spreadsheet::WriteExcel;
my $dbh = DBI->connect('dbi:mysql:database:3306','prithvi','prithvi') or die $dbh->errstr;
my $sth = $dbh->prepare("SELECT `AccNum`,`Type`,`Amount`,`ChequeNo`,`DDNo` FROM `transaction`");
$sth->execute or die $sth->errstr;
my $workbook = Spreadsheet::WriteExcel->new('query_result.xls');
my $worksheet = $workbook->add_worksheet();
my $row = 0;
my $col = 0;
my %h;
$worksheet->write_row($row++,$col,['Account Number','Cheque Debit','DD Debit','Cash Debit']);
while(my @data = $sth->fetchrow_array)
{
 next unless($data[1] eq 'Debit');
 my $result = $data[3] ? "ChequeNo" : $data[4] ? "DDNo" : "Cash";
 $h{$data[0]}{$result} += $data[2];
 $worksheet->write_row($row++,$col,\@data);
}
$sth->finish;
$dbh->disconnect;

我没有得到正确的输出。我哪里错了?请帮忙。提前致谢。我没有得到这个问题的答案,即主要将结果存储在电子表格中。请不要在回答之前关闭它。这是对你们所有人的一个非常善意的要求。

4

2 回答 2

2
   SELECT
    t1.AccountNumber, 
    SUM(t1.Amount)-(SELECT SUM(t2.Amount) from transaction t2 
     where t2.Type = 'Credit' 
     AND t2.AccountNumber = t1.AccountNumber) AS Subtraction
    from transaction t1
    WHERE t1.Type = 'Debit'
    group by t1.AccountNumber

结果:

ACCOUNTNUMBER   SUBTRACTION
016901581432    2500
016901581433    6000
016901581434    14500

已编辑 SQLFIDDLE 示例。

于 2012-10-05T07:57:48.307 回答
1

您似乎很好地掌握了如何与数据库交互并编写 SQL 查询。现在您只需将结果放入电子表格中。

如果您想要 Excel 电子表格,我建议您查看该Spreadsheet::WriteExcel模块。我过去用过这个,效果很好。以下是如何使用它的简要示例:

use DBI;
use strict;
use warnings;
use Spreadsheet::WriteExcel;

#
#Query the database here...
#


my $workbook = Spreadsheet::WriteExcel->new('query_results.xls');
my $worksheet = $workbook->add_worksheet();

my $row = 0;
my $col = 0;

#Write the column labels.
$worksheet->write_row($row++, $col, 
    ['Account Number','Type','Total Debit Amount']
);

while( my @data = $tran_cur->fetchrow_array)
{
    #Write an array into a row in the spreadsheet.
    $worksheet->write_row($row++, $col, \@data);
}

如果您不想要 Excel 电子表格,请尝试在CPAN中搜索所需格式的模块,或使用类似 Text::CSV创建可以轻松导入任何电子表格的 CSV 文件的方法。

于 2012-10-05T08:12:09.047 回答