Question

I'm trying get the subtotal at the end of the table for Accepted, cancelled, noShow and flagged...I try grouping but its throw an error. Is there any other or easy way to do it?

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 ???

Result I'm Looking for...

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
Was it helpful?

Solution

  1. Use UNION to combine two queries, first query would show the aggregate by group, second query would show the total

  2. To make sure the total is in the bottom, sort by an expression similar to this:

    Order by Case ComID when NULL then 'ZZZZZZ' else ComID end

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top