Hi, all, I could not find the solution for my problem.
I try to pivot several mySQL tables for reporting, the row number is not fixed so what I am doing now is that grouping it first as a subquery and then pivot it. It works fine with small number of rows but does not work with large number rows.
Here is an example, their are many cols, but only prod matters to me.
After grouping by prod, the table should beprod xx xx ... 'prod 1' 'prod 2' 'prod 1' 'prod 3' 'Prod 4' ......
prod count prod 1 10 prod 2 15 ......
Here is my code:
use DBI; my $dbh = connect(....); my $pvt_col = 'prod'; my $count = 'count'; my $table = 'prod' my $stmt = q{ SELECT CONCAT( '(SUM(CASE WHEN }. $pvt_col. q{ IS NULL THEN Count ELSE 0 END)) AS + Total, ', GROUP_CONCAT(DISTINCT CONCAT( '(SUM(CASE WHEN }. $pvt_col. q{ = ''', }. $pvt_col. q{, ''' T +HEN ', }. $count. q{, ' ELSE 0 END)) AS `', }. $pvt_col. q{, '`' ) ) ) FROM ( SELECT }. $pvt_col. q{, count(*) AS }. $count. q{ FROM }. $table. q{ GROUP BY }. $pvt_col. q{ WITH ROLLUP) as temptbl;}; my $sth = $dbh->prepare($stmt); $sth->execute(); my $tmp; while ( ($tmp) = $sth->fetchrow_array() ) { print"$tmp\n"; last; }
The expected output should be:
(SUM(CASE WHEN prod IS NULL THEN Count ELSE 0 END)) AS Total, (SUM(CASE WHEN prod = 'prod1' THEN 10 ELSE 0 END)) AS `prod1`, (SUM(CASE WHEN prod = 'prod2' THEN 15 ELSE 0 END)) AS `prod2`, (SUM(CASE WHEN prod = 'prod3' THEN 1 ELSE 0 END)) AS `prod3`, .....
After this, I can query again to produce pivot results:
$statement is like:my $statement = q{ SELECT }. $tmp. q{ FROM( SELECT }. $pvt_col. q{, count(*) AS }. $count. q{ FROM }. $table. q{ GROUP BY }. $pvt_col. q{ WITH ROLLUP ) as temptbl;}; $sth = $dbh->prepare($statement); ....
SELECT ( (SUM(CASE WHEN prod IS NULL THEN Count ELSE 0 END)) AS Total, (SUM(CASE WHEN prod = 'prod1' THEN 10 ELSE 0 END)) AS `prod1`, (SUM(CASE WHEN prod = 'prod2' THEN 15 ELSE 0 END)) AS `prod2`, (SUM(CASE WHEN prod = ..... ... FROM( SELECT prod, count(*) AS Count FROM prod GROUP BY prod WITH ROLL +UP) as temptbl;
It works beautifully for tables with small number of rows, but failed for tables with larger number of rows. $tmp is trucated when I have large rows. So $statement cannot be excuted successfully.
Monks, any help is highly appreciated!
Environment: Perl 5.14.2, ubuntu 12.04.2, MySQL 5.5.31
In reply to return string from query (DBI, MySQL) got truncated when trying to generating statement dynamically for MySQL by khandielas
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |