mysql:ROLLUP在TOP,SUM(FINANCIAL AMOUNT),然后由DATETIME DESC订购FINANCIAL AMOUNT列

时间:2014-06-11 01:48:41

标签: php mysql sql sql-order-by rollup

表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


表2

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

pkFinancialEntryID FinancialEntry 1 Credit 2 Debit


表3

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

pkUserID UserName 1 Test User


表4

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

pkProfileID fkUserID 1 1


所需的查询结果:

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

2 个答案:

答案 0 :(得分:1)

我会留下借记/贷记的东西,以便合并:

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

答案 1 :(得分:0)

ORDER BY CASE WHEN pkID IS NULL THEN 0 ELSE 1 END, EntryTotalAmount
对于汇总行,

pkID将为null。通过将null映射到0而不是null到1,我们确保首先对已汇总的行进行排序,然后将EntryTotalAmount用于这些分区内的内部排序。

更新了Queury

SELECT ifnull(pkFinancialID,'Total Due:') as pkFinancialID , CASE WHEN fkFinancialEntryID = 1 THEN 1 ELSE -1 END * SUM(FinancialAmount) as FinancialTotalAmount , FinancialAmount, FinancialDescription, FinancialDateTime, fkUserID FROM ( select pkFinancialID, fkFinancialCodeTypeID, fkFinancialEntryID , CASE WHEN fkFinancialEntryID = 1 THEN 1 ELSE -1 END * SUM(FinancialAmount) as FinancialTotalAmount , FinancialAmount, FinancialDescription, FinancialDateTime, fkUserID , fkProfileID from tblFinancials WHERE tblFinancials.fkUserID = 1 AND tblFinancials.fkProfileID = 1 group by pkFinancialID with rollup ) r WHERE r.fkUserID = 1 AND r.fkProfileID = 1 ORDER BY CASE WHEN pkFinancialID IS NULL THEN 0 ELSE 1 END, FinancialTotalAmount;