查询结果表末尾的子总计

时间:2012-08-30 17:32:20

标签: mysql sql sum subtotal

我正在尝试在表的末尾获取Accepted,cancelled,noShow和flagged的小计...我尝试分组但是它抛出一个错误。有没有其他或简单的方法来做到这一点?

Select * From (
SELECT 
c.ComID, ISNULL(c.Client,'-') AS Driver_Name, GROUPING(c.MTNum) WHILE 1 THEN 'TOTAL' ELSE ISNULL(c.MTNum,'-'), ISNULL(Accepted,0) AS Accepted, ISNULL(Cancelled,0) AS Cancelled, ISNULL(NoShow,0) AS No_Show, ISNULL(Flagged,0) AS Flagged
FROM
(SELECT 
    HistoryLTD.CompanyID, HistoryLTD.Client, HistoryLTD.MTNum
FROM
    HistoryLTD
GROUP BY HistoryLTD.Client, HistoryLTD.CompanyID, HistoryLTD.MTNum) c
    LEFT JOIN
(SELECT 
    HistoryLTD.MTNum, count(HistoryLTD.MTNum) AS Cancelled
FROM
    HistoryLTD
WHERE
    HistoryLTD.Notes LIKE '%Cancelled%' AND TimeAssigned > '2011-08-28' AND TimeAssigned < '2011-08-30'
GROUP BY HistoryLTD.MTNum) c1 ON c.MTNum = c1.MTNum
    LEFT JOIN
(SELECT 
    HistoryLTD.MTNum, count(HistoryLTD.MTNum) AS NoShow
FROM
    HistoryLTD
WHERE
    HistoryLTD.Notes LIKE '%No Show%' AND TimeAssigned > '2011-08-28' AND TimeAssigned < '2011-08-30'
GROUP BY HistoryLTD.MTNum) c2 ON c.MTNum = c2.MTNum
    LEFT JOIN
(SELECT 
    HistoryLTD.MTNum, count(HistoryLTD.MTNum) AS Flagged
FROM
    HistoryLTD
WHERE
    HistoryLTD.Notes LIKE '%Flagged%' AND TimeAssigned > '2011-08-28' AND TimeAssigned < '2011-08-30'
GROUP BY HistoryLTD.MTNum) c3 ON c.MTNum = c3.MTNum
LEFT JOIN
(SELECT 
    HistoryLTD.MTNum, count(HistoryLTD.MTNum) AS Accepted
FROM
    HistoryLTD
where 
    Notes Not LIKE '%Cancelled%'
    OR Notes Not LIKE '%No Show%'
    OR Notes Not LIKE '%Flagged%'
    AND TimeAssigned > '2011-08-28' AND TimeAssigned < '2011-08-30'
GROUP BY HistoryLTD.MTNum) c4 ON c.MTNum = c4.MTNum ) firstQuery
UNION
Select Null, Null, 'Total', SUM(Accepted), SUM(Cancelled), SUM(No_Show), SUM(Flagged)
  FROM ???

结果我正在寻找......

ComID   Client_Name mtNum   acc canc    noshow  Flgd
CTBV    Brian       3834    19  0   5   1
CTBV    Central     3863    5   0   0   5
CTBV    Charles     3815    25  0   2   5
CTBV    Chris       3842    14  0   0   0
CTBV    Chris       3864    17  0   1   0
CTBV    Cory        3829    15  0   1   1
               TOTAL        95  0   9   12   <-- This total at bottom

1 个答案:

答案 0 :(得分:1)

  1. 使用UNION组合两个查询,第一个查询将按组显示聚合,第二个查询将显示总计

  2. 要确保总数位于底部,请使用与此类似的表达式进行排序:

    按NULL时按Case ComID排序然后'ZZZZZZ'其他ComID结束