Newbee Newbee - 1 month ago 7
SQL Question

Add a row to display sum in the last column

I have the below query:

SELECT
cc.chain_desc as chain_desc
,cc.chain_id as chain_id
,COUNT(distinct t.trans_id) as TranCount
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
GROUP BY cc.chain_desc, cc.chain_id
ORDER BY cc.chain_desc, cc.chain_id


When I execute the query, I get the below result:

enter image description here

But, I need to add a row "Total" which will display a sum of all transactions in the last column as below:

enter image description here

What changes should I make in the query to display the above result??.

I have tried using rollup as shown below, but I didnt get the expected result:

SELECT
cc.chain_desc as chain_desc
,cc.chain_id as chain_id
,COUNT(distinct t.trans_id) as TranCount
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
GROUP BY cc.chain_desc, cc.chain_id with Rollup
ORDER BY cc.chain_desc, cc.chain_id

Answer

A simple way is the use of UNION with a select for total

SELECT 
     cc.chain_desc as chain_desc 
    ,cc.chain_id as chain_id 
    ,COUNT(distinct t.trans_id) as TranCount
FROM TRANSACTION AS t 
LEFT OUTER JOIN location AS l 
ON t.location_id = l.location_id 
LEFT OUTER JOIN trans_line AS tl 
ON t.trans_id = tl.trans_id 
LEFT OUTER JOIN contract as c 
ON t.contract_id = c.contract_id 
LEFT OUTER JOIN chain_desc as cc 
ON l.chain_id = cc.chain_id 
WHERE 
t.loc_country = 'U' 
AND c.issuer_id IN (156966,166203) 
AND t.trans_date >= '2016-10-01 00:00' 
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC') 
GROUP BY cc.chain_desc, cc.chain_id 
ORDER BY cc.chain_desc, cc.chain_id

UNION 

SELECT 
    'TOTAL'
    null
    ,COUNT(distinct t.trans_id) 
FROM TRANSACTION AS t 
LEFT OUTER JOIN location AS l 
ON t.location_id = l.location_id 
LEFT OUTER JOIN trans_line AS tl 
ON t.trans_id = tl.trans_id 
LEFT OUTER JOIN contract as c 
ON t.contract_id = c.contract_id 
LEFT OUTER JOIN chain_desc as cc 
ON l.chain_id = cc.chain_id 
WHERE 
t.loc_country = 'U' 
AND c.issuer_id IN (156966,166203) 
AND t.trans_date >= '2016-10-01 00:00' 
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')