Search code examples
phpmysqlsqlsql-order-byrollup

mysql: ROLLUP on TOP, SUM(FINANCIAL AMOUNT), then order FINANCIAL AMOUNT column by DATETIME DESC


Table 1

CREATE TABLE tblFinancials
(
pkFinancialID int(11) NOT NULL AUTO_INCREMENT,
fkUserID int(11),
fkProfileID int(11),
fkFinancialEntryID int(11),
FinancialAmount decimal(10,2),
FinancialDateTime datetime
);

pkFinancialID fkUserID fkProfileID fkFinancialEntryID FinancialAmount FinancialDateTime 1 1 1 1 100.00 2014-06-07 07:00:00 2 1 1 2 100.00 2014-06-08 08:00:00


Table 2

CREATE TABLE tblFinancialEntry
(
pkFinancialEntryID int(11) NOT NULL AUTO_INCREMENT,
FinancialEntry varchar(255)
);

pkFinancialEntryID FinancialEntry 1 Credit 2 Debit


Table 3

CREATE TABLE tblUsers
(
pkUserID int(11) NOT NULL AUTO_INCREMENT,
UserName varchar(255)
);

pkUserID UserName 1 Test User


Table 4

CREATE TABLE tblProfiles
(
pkProfileID int(11) NOT NULL AUTO_INCREMENT,
fkUserID int(11),
ProfileName varchar(255)
);

pkProfileID fkUserID 1 1


Desired query result:

Total Due:      0.00
             -100.00   2014-06-07 07:00:00
              100.00   2014-06-08 08:00:00

Solution

  • I'll leave the debit/credit thing for you to incorporate:

    select concat(
       case when T.pkFinancialID is null 
            then 'Total Due:     '
            else '               '
       end,  cast(FinancialTotalAmount as char(20))
       ) 
    
     , case when T.pkFinancialID is null
            then null
            else FDateTime
       end
    from (
        select pkFinancialID
         , max(FinancialDateTime) as FDateTime
         , SUM(CASE WHEN fkFinancialEntryID = 1 
                    THEN 1 
                    ELSE -1 
           END * FinancialAmount) as FinancialTotalAmount
        from tblFinancials 
        WHERE tblFinancials.fkUserID = 1 
          AND tblFinancials.fkProfileID = 1 
        group by pkFinancialID with rollup
    ) as T  
    order by case when T.pkFinancialID is null then 0 else 1 end
           , FDateTime;
    
    
    Total Due: 0.00     (null)
             100.00     June, 07 2014 07:00:00+0000
            -100.00     June, 08 2014 08:00:00+0000