Create a grand total row in sql server - sql-server

I'm writing a query where in there should be a total row at the end of the table that gives the sum of the closed , open, reassigned columns.
I'm able to make a pivot, but unable to know how to place a row in the end. I've searched online but mostly found solutions for creating a column and a row or just column. I'm into Dev, dunno much about the databases. below is my pivot. please let me know how can i do this.
select *
from
(
select [case owner] as AGENT, [final status]
from StatusTable
) src
pivot
(
count([final status])
for [final status] in ([CLOSED], [OPEN], [REASSIGNED])
) piv
The current output is as below image
And here I want an extra row as shown below.
TOTAL | 2 | 8 | 2

You can use UNION ALL to concat rowsets with identical columns:
with ctePivot as (
select *
from
(
select [case owner] as AGENT, [final status]
from StatusTable
) src
pivot
(
count([final status])
for [final status] in ([CLOSED], [OPEN], [REASSIGNED])
) piv
)
select * from ctePivot
union all
select 'TOTAL', sum([CLOSED]), sum([OPEN]), sum([REASSIGNED]) from ctePivot
Or the simpler variant with only a GROUP BY ROLLUP:
select ISNULL([case owner], 'TOTAL') as AGENT,
SUM(CASE WHEN [final status]='CLOSED' THEN 1 ELSE 0 END) [CLOSED],
SUM(CASE WHEN [final status]='OPEN' THEN 1 ELSE 0 END) [OPEN],
SUM(CASE WHEN [final status]='REASSIGNED' THEN 1 ELSE 0 END) [REASSIGNED]
from StatusTable
GROUP BY ROLLUP ([case owner]);

Assuming agent is a key field, you can aggregate on that and use GROUP BY ROLLUP():
select coalesce(piv.agent,'Grand Total') agent
,sum(piv.closed) closed
,sum(piv.open) open
,sum(piv.reassigned) reassigned
from
(
select [case owner] as AGENT, [final status]
from StatusTable
) src
pivot
(
count([final status])
for [final status] in ([CLOSED], [OPEN], [REASSIGNED])
) piv
group by rollup(piv.agent)

If you write your query as a group by instead of a pivot, you can use with rollup to get your total row. E.g.:
select
[AGENT] = case when grouping([case owner])=1 then 'TOTAL' else [case owner] end,
[CLOSED] = sum(case when [final status] = 'CLOSED' then 1 else 0 end),
[OPEN] = sum(case when [final status] = 'OPEN' then 1 else 0 end),
[REASSIGNED] = sum(case when [final status] = 'REASSIGNED' then 1 else 0 end)
from StatusTable
group by [case owner]
with rollup
http://sqlfiddle.com/#!3/e0bb5/8/0

Related

multiple column pivot in sql server

I have some issue about how to make query result like
this is what i've tried,, but not exactly same like what i mean
CREATE TABLE #dta
(
Data [nvarchar](max),
Date [varchar] (12) ,
GR [int] ,
Refund [int] ,
Sales [int] ,
)
INSERT INTO #dta
SELECT 'asd',1,10,0,0 UNION ALL
SELECT 'asd',2,0,0,4 UNION ALL
SELECT 'asd',3,4,1,1 UNION ALL
SELECT 'qwe',1,2,0,0 UNION ALL
SELECT 'qwe',3,0,0,1 UNION ALL
SELECT 'zxc',1,0,0,5 UNION ALL
SELECT 'zxc',2,4,0,1 UNION ALL
SELECT 'zxc',3,0,1,5
--Only for sales
SELECT data, [1],[2],[3] FROM
(SELECT data, [date] , Sales FROM #dta )Tab1
PIVOT
(
SUM(Sales) FOR [date] IN ([1],[2],[3])) AS Tab2
ORDER BY Tab2.Data
You can use conditional aggregation and try something along this code:
SELECT t.[Data]
,MAX(CASE WHEN t.[Date]=1 THEN t.Sales END) AS [Sales_Date_1]
,MAX(CASE WHEN t.[Date]=1 THEN t.Refund END) AS [Refund_Date_1]
,MAX(CASE WHEN t.[Date]=1 THEN t.GR END) AS [GR_Date_1]
,MAX(CASE WHEN t.[Date]=2 THEN t.Sales END) AS [Sales_Date_2]
,MAX(CASE WHEN t.[Date]=2 THEN t.Refund END) AS [Refund_Date_2]
,MAX(CASE WHEN t.[Date]=2 THEN t.GR END) AS [GR_Date_2]
,MAX(CASE WHEN t.[Date]=3 THEN t.Sales END) AS [Sales_Date_3]
,MAX(CASE WHEN t.[Date]=3 THEN t.Refund END) AS [Refund_Date_3]
,MAX(CASE WHEN t.[Date]=3 THEN t.GR END) AS [GR_Date_3]
FROM #dta t
GROUP BY t.[Data];
If the count of t.[Date] (1 to 3 in your example data) is not limited to a known maximum, you'd have to create the statement dyanmically.
If your t.[Date] column is a date value actually and you want your output columns named after some date values (unpredictable column alias) within your set, you must create this dynamically too.

PIvot with multiple result values

im trying to put multiple sums in this pivot table but i havent been succeful,
This is the Raw data
from
select
billname,
orderperiodyear,
Sum_buyprice,
Sum_Sellprice,
Tonnage
From Sum_Orders
This is my pivot how can i include buy price and tonnage in the pivot results
SELECT billname,SUM([2017])AS '2017', SUM([2016]) AS '2016'
FROM Sum_Orders
PIVOT
(
SUM(Sum_SellPrice)
FOR OrderperiodYear IN ([2017],[2016])
)AS pvt
WHERE OrderStatus IN ('Complete', 'Invoiced')
AND ( (MONTH(OrderDate) = MONTH(GETDATE()) AND day(OrderDate) <= DAY(GETDATE()))
OR MONTH(OrderDate) < MONTH(GETDATE()))
Group by BILLNAME
HAVING COALESCE(SUM([2017]), SUM([2016])) IS NOT NULL
ORDER BY BILLNAME ASC
This is what i get from my pivot
Im looking for something like this
You first have to do unpivot first DEMO
SELECT billname,
CAST([OrderperiodYear] as varchar(500)) + '_' + CAST([attribute] as varchar(500)) as attribute,
[data]
FROM (SELECT billname,
[OrderperiodYear],
[Sum_Buyprice] as Buy,
[Sum_Sellprice] as Sell,
[Tonnage] as Ton
FROM records) p
UNPIVOT
([data] FOR [attribute] IN
(Buy, Sell, Ton)
) as unpvt
OUTPUT
Then you can create a Dynamic Pivot.
One option is to skip pivot() and go for the old style cross tab.
select
billname
, [2016_buyprice] = sum(case when OrderPeriodYear = 2016 then sum_buyprice else null end)
, [2017_buyprice] = sum(case when OrderPeriodYear = 2017 then sum_buyprice else null end)
, [2016_sellprice] = sum(case when OrderPeriodYear = 2016 then sum_sellprice else null end)
, [2017_sellprice] = sum(case when OrderPeriodYear = 2017 then sum_sellprice else null end)
, [2016_tonnage] = sum(case when OrderPeriodYear = 2016 then tonnage else null end)
, [2017_tonnage] = sum(case when OrderPeriodYear = 2017 then tonnage else null end)
from sum_orders
where OrderStatus in ('Complete', 'Invoiced')
and ((month(OrderDate) = month(getdate())
and day(OrderDate) <= day(getdate()))
or month(OrderDate) < month(getdate()))
group by billname
order by billname asc

SQL query SUM() AND GROUP BY for 2 columns in a table

I am using Microsoft Sql Server management studio.
I have had mixed success creating a tax report for a particular type of invoice that I have.
I have amounts under 6%, other amounts under 13.5% and the last amount has a complete total of both 6% and 13.5%.
I have got my answer in the results, but two different rows for each invoice are displayed. One is for 6% values and the other for 13.5% values.
I need to somehow merge these two rows into one single row for each invoice.
My Sql query is as follows:
SELECT tran_no ,
tran_date ,
( SELECT SUM(edetail_amt)
WHERE edetail_taxid = '6008U_='
) AS '6% amt' ,
( SELECT SUM(edetail_per)
WHERE edetail_taxid = '6008U_='
) AS '6% vat' ,
( SELECT SUM(edetail_amt)
WHERE edetail_taxid = '6008U_>'
) AS '13.5% amt' ,
( SELECT SUM(edetail_per)
WHERE edetail_taxid = '6008U_>'
) AS '13.5% vat' ,
( SELECT SUM(edetail_amt + edetail_per)
WHERE edetail_taxid IN ( '6008U_=', '6008U_>' )
) AS 'Net Total'
FROM h_edetail
INNER JOIN h_tran ON edetail_tranid = tran_kid
WHERE tran_trantype = 'PI'
AND tran_date = '2016-11-03 00:00:00.000'
GROUP BY tran_no ,
tran_date ,
edetail_taxid
ORDER BY tran_no;
A screenshot of the query along with the results are as follows:
If am not wrong you are looking for this
SELECT tran_no,
tran_date,
Sum(case when edetail_taxid = '6008U_=' then edetail_amt else 0 end) AS '6% amt',
Sum(case when edetail_taxid = '6008U_=' then edetail_per else 0 end) AS '6% vat',
Sum(case when edetail_taxid = '6008U_>' then edetail_amt else 0 end) AS '13.5% amt',
Sum(case when edetail_taxid = '6008U_>' then edetail_per else 0 end) AS '13.5% vat',
Sum(case when edetail_taxid IN ( '6008U_=', '6008U_>' ) then edetail_amt + edetail_per else 0 end) AS 'Net Total'
FROM h_edetail
INNER JOIN h_tran
ON edetail_tranid = tran_kid
WHERE tran_trantype = 'PI'
AND tran_date = '2016-11-03 00:00:00.000'
GROUP BY tran_no,
tran_date
ORDER BY tran_no
Because of select sum(edetail_amt) where edetail_taxid='6008U_=' you are forced to add edetail_taxid in group by that is the reason for duplicate records. You can do that by adding case inside SUM aggregate

how to join table group by count

I have query_1:
select id,
count(case when no01 ='B' then 1 END) +
count(case when no02='B' then 1 END) +
count(case when no03='B' then 1 END) as Count_All
From tabel_a
where date ='20150201'
group by id
and also I have query_2:
select id, COUNT (*) from tabel_b
where ids <> 'T' and idt ='C'
group by id
How can I join query_1 with query_2 via id?
You could try using sub selects. Something like
SELECT *
FROM (
select id,
count(case when no01 ='B' then 1 END) + count(case when no02='B' then 1 END) + count(case when no03='B' then 1 END) as Count_All
From tabel_a
where date ='20150201'
group by id
) a INNER JOIN
(
select id,
COUNT (*) cnt
from tabel_b
where ids <> 'T'
and idt ='C'
group by id
) b ON a.ID = b.ID
Seeing as you specified SQL Server, you could also make use of a Common Table Expression.
Something like
;WITH a AS (
select id,
count(case when no01 ='B' then 1 END) + count(case when no02='B' then 1 END) + count(case when no03='B' then 1 END) as Count_All
From tabel_a
where date ='20150201'
group by id
)
, b as (
select id,
COUNT (*) cnt
from tabel_b
where ids <> 'T'
and idt ='C'
group by id
)
SELECT *
FROm a INNER JOIN
b ON a.ID = b.ID

Help with finding the difference (delta) from a value returned from the last two records

I'm using MS SQL 2005 and I have created a CTE query to return values from the last two records. I then use this to find the delta of two figures returned. I have a working query of sorts but
I'm having problems getting anything other than the delta figure.
here is my query:
;with data as(
SELECT
NetObjectID,
RawStatus,
RowID,
rn
from(
SELECT
CustomPollerAssignmentID AS NetObjectID,
RawStatus,
RowID,
row_number() over(order by DateTime desc)as rn
FROM CustomPollerStatistics_Detail
WHERE
(CustomPollerAssignmentID='a87f531d-4842-4bb3-9d68-7fd118004356')
) x where rn<=2
)
SELECT
case when
max(case rn when 1 then RawStatus end) > max(case rn when 2 then RawStatus end)
then
max(case rn when 1 then RawStatus end) - max(case rn when 2 then RawStatus end)
else
max(case rn when 2 then RawStatus end) - max(case rn when 1 then RawStatus end)
end as Delta
from data having
(SELECT
case when
max(case rn when 1 then RawStatus end) > max(case rn when 2 then RawStatus end)
then
max(case rn when 1 then RawStatus end) - max(case rn when 2 then RawStatus end)
else
max(case rn when 2 then RawStatus end) - max(case rn when 1 then RawStatus end)
end
from data) >= 1
What I'm after is to get the Delta & NetObjectID returned. Each time I try, I get errors.
data.NetObjectID is invalid in the select list because it is not contained in either an aggregate function or the group by clause.
If I try adding group by etc.. to the end of the query I get further error complaining about the word 'group'.
I'm relatively new to SQL and I am picking things up as I go. Any help would be gratefully received.
see if something like this will work.
;with data as
(
SELECT
NetObjectID,
RawStatus,
RowID,
rn
from
(
SELECT
CustomPollerAssignmentID AS NetObjectID,
RawStatus,
RowID,
row_number() over(order by DateTime desc)as rn
FROM CustomPollerStatistics_Detail
WHERE
(
CustomPollerAssignmentID='a87f531d-4842-4bb3-9d68-7fd118004356'
)
) x
where rn<=2
)
select
NetObjectID,
max(RawStatus)-min(RawStatus) as Delta
from data
group by NetObjectID
Sorry, I'm very new here and I'm unsure of CTE queries, however it looks like after you define Data, you are selecting case ... as Delta FROM.... Meaning you only have Delta in your select statement. Again, sorry if I'm way off base.

Resources