SQL Pivot Table from query - sql

How can I convert this query to pivot
select
branch,
months,
[Parts Revenue Budget]
from #Temp1
Result
Desired Output

You can use conditional aggregation :
SELECT t.branch,
SUM(CASE WHEN t.months = 'JAN' THEN t.[Parts Revenue Budget] ELSE 0 END) as JAN,
SUM(CASE WHEN t.months = 'FEB,' THEN t.[Parts Revenue Budget] ELSE 0 END) as FEB
... As many as you need
SUM(t.[Parts Revenue Budget]) as grandtotal
FROM #Temp1
GROUP BY t.branch
UNION ALL
SELECT 'Grand Total',
SUM(CASE WHEN t.months = 'JAN' THEN t.[Parts Revenue Budget] ELSE 0 END) as JAN,
SUM(CASE WHEN t.months = 'FEB' THEN t.[Parts Revenue Budget] ELSE 0 END) as FEB,
... As many as you need
SUM(t.[Parts Revenue Budget]) as grandtotal
FROM #Temp1 t

SELECT BRANCH,
SUM(CASE WHEN MONTHS = 'JAN' THEN PARTSREVENUEBUDJET END) AS [JAN],
SUM(CASE WHEN MONTHS = 'FEB' THEN PARTSREVENUEBUDJET END) AS [FEB],
SUM(CASE WHEN MONTHS = 'MAR' THEN PARTSREVENUEBUDJET END) AS [MARCH],
SUM(CASE WHEN MONTHS = 'APR' THEN PARTSREVENUEBUDJET END) AS [APR],
SUM(CASE WHEN PONITS = 'MAY' THEN PARTSREVENUEBUDJET END) AS [MAY],
SUM(CASE WHEN MONTHS = 'JUNE' THEN PARTSREVENUEBUDJET END) AS [JUNE],
SUM(CASE WHEN MONTHS = 'JULY' THEN PARTSREVENUEBUDJET END) AS [JULY],
SUM(CASE WHEN MONTHS = 'AUG' THEN PARTSREVENUEBUDJET END) AS [AUG],
SUM(CASE WHEN MONTHS = 'SEP' THEN PARTSREVENUEBUDJET END) AS [SEP],
SUM(CASE WHEN MONTHS = 'OCT' THEN PARTSREVENUEBUDJET END) AS [OCT],
SUM(CASE WHEN MONTHS = 'NOV' THEN PARTSREVENUEBUDJET END) AS [NOV],
SUM(CASE WHEN MONTHS = 'NOV' THEN PARTSREVENUEBUDJET END) AS [DEC],
SUM(PARTSREVENUEBUDJET) AS 'GRANDTOTAL'
FROM TABLE
GROUP BY BRANCH
2)
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(months)
from #TEMP1
group by months
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT branch,' + #cols + ',tiot from
(
select *,sum(BUDGET)over(partition by branch) as tiot
from #TEMP1
) x
pivot
(
sum(BUDGET)
for months in (' + #cols + ')
) p '
exec(#query);

I tried as follows:
CREATE TABLE #TEMP1(BRANCH VARCHAR(100),MONTHS VARCHAR(100),BUDGET varchar(100))
INSERT INTO #TEMP1 VALUES ('CPD','APR','801375')
INSERT INTO #TEMP1 VALUES ('Sabzi Mandi','APR','1033697')
INSERT INTO #TEMP1 VALUES ('DHA','APR','2119835')
INSERT INTO #TEMP1 VALUES ('Quidabad','APR','2100042')
INSERT INTO #TEMP1 VALUES ('Sukkar','AUG','44377320')
INSERT INTO #TEMP1 VALUES ('Baghbanpura','AUG','2726114')
INSERT INTO #TEMP1 VALUES ('Multan','AUG','6068565')
select *,coalesce(CAST(AUG AS NUMERIC(10,2)),0)+coalesce(CAST(apr AS NUMERIC(10,2)),0) as 'grand total'
from
(select branch , months ,budget from #temp1) as s
pivot
(MAX(BUDGET) for months in (APR,AUG)) AS PVT

CREATE TABLE TEMP1(BRANCH VARCHAR(100),MONTHS VARCHAR(100),BUDGET FLOAT(126));
INSERT INTO TEMP1 VALUES ('ABC','AUG','1000');
INSERT INTO TEMP1 VALUES ('PQR','APR','2000');
INSERT INTO TEMP1 VALUES ('XYZ','AUG','1000');
SELECT
BRANCH,
APR,
AUG,
(NVL(APR,'0')+NVL(AUG,'0')) AS GRANDTOTAL
FROM
(SELECT
*
FROM
(
SELECT
BRANCH,
MONTHS,
BUDGET
FROM
TEMP1
)
pivot ( MIN(BUDGET) FOR MONTHS IN ('APR' AS APR,'AUG' AS AUG)))
UNION ALL
SELECT 'GRAND TOTAL' AS BRANCH,SUM(APR) AS APR, SUM(AUG) AS AUG, SUM(GRANDTOTAL) AS GRANDTOTAL
FROM
(SELECT
BRANCH,
APR,
AUG,
(NVL(APR,'0')+NVL(AUG,'0')) AS GRANDTOTAL
FROM
(SELECT
*
FROM
(
SELECT
BRANCH,
MONTHS,
BUDGET
FROM
TEMP1
)
pivot ( MIN(BUDGET) FOR MONTHS IN ('APR' AS APR,'AUG' AS AUG) )));

Related

SQL query for multiple where clause

I have a table named tbl_transactions with columns
Category (string)
for_month (string)
Vehicle_No (string)
amount (float)
As shown below in the
.
Is it possible to get the total amount for each month and the result should be category wise something like
You can use the conditional aggregation as follows:
SELECT CATEGORY,
SUM(CASE WHEN FOR_MONTH = 'April' THEN AMOUNT END) AS APRIL_AMOUNT,
SUM(CASE WHEN FOR_MONTH = 'May' THEN AMOUNT END) AS MAY_AMOUNT,
SUM(CASE WHEN FOR_MONTH = 'June' THEN AMOUNT END) AS JUNE_AMOUNT
FROM YOUR_tABLE T
WHERE FOR_MONTH IN ('April', 'May', 'June')
GROUP BY CATEGORY
Using PIVOT
DECLARE #t TABLE(Cat VARCHAR(MAX), Mon VARCHAR(MAX),Amt INT)
INSERT INTO #T VALUES('Registration','April',850),
('Registration','April',450),
('Registration','April',295)
SELECT Cat, [April] AS [Total Amt in Apr],
[May] AS [Total Amt in May],
[June] AS [Total Amt in June]FROM
(
SELECT
Cat,
Mon,
Amt
FROM
#T
) t
PIVOT(
SUM(Amt)
FOR Mon IN (
[April],
[May],
[June]
)
) AS pivot_table;
Results:
Cat Total Amt in Apr Total Amt in May Total Amt in June
Registration 1595 NULL NULL

How to the add balance in the next field amount, per Vendorname , per month/year

Good day guys . In my query I want to add the current balance (from previous payable )to the next field amount and subtract it to the payment made (paid field)
sample codes
select a.vendorname
,DATENAME(month ,(cdvdate)) as Month
,year(cdvdate) as Year
, sum(b.credit) as Amount
, sum(b.debit) as Paid
, sum(b.credit)- sum(b.debit) as balance
from (select cdvno,acct
, sum(case when credit = 0 then debit else 0 end) as debit
, sum(case when debit = 0 then credit else 0 end)as credit
, trantype
from cdvdtl
group by cdvno,acct, trantype
)b
left join cdvhdr a
on b.cdvno = a.cdvno and b.trantype = a.trantype
left join account c on b.acct = c.acct
where b.acct='2122102'
group by a.vendorname,year(cdvdate),DATENAME(month ,(cdvdate))
order by Vendorname,case year(cdvdate)
when '2016' then 1
when '2017' then 2
when '2018' then 3
when '2019' then 4
end
,case DATENAME(month ,(cdvdate))
when 'January' then 1
when 'February' then 2
when 'March' then 3
when 'April' then 4
when 'May' then 5
when 'June' then 6
when 'July' then 7
when 'August' then 8
when 'September' then 9
when 'October' then 10
when 'November' then 11
when 'December' then 12
end
I tried using row number but it doesn't work the way i want
i want the result to be something like this . Thank you so much enlighten me please
Try this:
with cte as
(
select t2.vendorname as vendorname,
convert(char(7), t1.cdvdate, 120) as YYYMM,
DATEPART(month, t1.cdvdate) as MM,
datepart(year, t1.cdvdate) as YYYY,
sum(case when t1.credit = 0 then t1.debit else 0 end) as debit,
sum(case when t1.debit = 0 then t1.credit else 0 end) as credit,
ROW_NUMBER() over (
partition by vendorname
order by convert(char(7), t1.cdvdate, 120)
) as rn
from cdvdtl t1
inner join cdvhdr t2 on t2.cdvno = t1.cdvno
and t2.trantype = t1.trantype
group by t2.vendorname,
convert(char(7), t1.cdvdate, 120),
DATEPART(month, t1.cdvdate),
datepart(year, t1.cdvdate)
)
select t1.vendorname as vendorname,
t1.MM as MM,
t1.YYYY as YYYY,
t1.credit as Amount,
t1.debit as Paid,
t1.debit-t1.credit as Balance,
t2.debit-t2.credit as BalanceBegin
from cte t1
left join cte t2 on t2.vendorname = t1.vendorname
and t2.rn = t1.rn-1
order by t1.vendorname,
t1.YYYMM

SQL Server Pivot Row Total

I'm using SQL Server 2012 and have the below pivot code that works fine. However, how do I include a row total i.e. a sum of the recorded amount for each account over the course of the year?
SELECT *
FROM (
SELECT [Account],[AccountDesc], CONVERT(CHAR(4), AccDate, 100) as [Month], [RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE [Employee] = #Employee
) AS s
PIVOT
(
SUM ([RecordedAmount])
FOR [Month] in (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sept, Oct, Nov, Dec)
) As pvt
Any help would be greatly appreciated.
If anyone is interested this is the final working solution:
SELECT pvt.* ,Isnull(pvt.jan,0) +Isnull(pvt.feb,0) +Isnull(pvt.mar,0) +Isnull(pvt.apr,0) +Isnull(pvt.may,0) +Isnull(pvt.jun,0) +Isnull(pvt.jul,0) +Isnull(pvt.aug,0) +Isnull(pvt.sept,0) +Isnull(pvt.oct,0) +Isnull(pvt.nov,0) as YearTotal
FROM (
SELECT [Account],[AccountDesc], CONVERT(CHAR(4), AccDate, 100) as [Month], [RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE [Employee] = #Employee
) AS s
pivot (
SUM ([RecordedAmount])
FOR [Month] in (May, Jun, Jul, Aug, Sept, Oct, Nov, Dec, Jan, Feb, Mar, Apr)
) As pvt
this would also work for you and might perform better
SELECT [Account],
[AccountDesc],
SUM(CASE WHEN [Month] = 'Jan' THEN [RecordedAmount] END) AS [Jan],
SUM(CASE WHEN [Month] = 'Feb' THEN [RecordedAmount] END) AS [Feb],
SUM(CASE WHEN [Month] = 'Mar' THEN [RecordedAmount] END) AS [Mar],
SUM(CASE WHEN [Month] = 'Apr' THEN [RecordedAmount] END) AS [Apr],
SUM(CASE WHEN [Month] = 'May' THEN [RecordedAmount] END) AS [May],
SUM(CASE WHEN [Month] = 'Jun' THEN [RecordedAmount] END) AS [Jun],
SUM(CASE WHEN [Month] = 'Jul' THEN [RecordedAmount] END) AS [Jul],
SUM(CASE WHEN [Month] = 'Aug' THEN [RecordedAmount] END) AS [Aug],
SUM(CASE WHEN [Month] = 'Sept' THEN [RecordedAmount] END) AS [Sept],
SUM(CASE WHEN [Month] = 'Oct' THEN [RecordedAmount] END) AS [Oct],
SUM(CASE WHEN [Month] = 'Nov' THEN [RecordedAmount] END) AS [Nov],
SUM(CASE WHEN [Month] = 'Dec' THEN [RecordedAmount] END) AS [Dec],
SUM([RecordedAmount]) AS [Total]
FROM (
SELECT [Account],
[AccountDesc],
CONVERT(CHAR(4),AccDate,100) AS [Month],
[RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE [Employee] = #Employee
) t
GROUP BY [Account],
[AccountDesc]
works the same as pivot but gives a little more control when including extra information.

Month and year wise report

I want to show a table that months are vertical and years are horizontal, I give an input of year and month that is from a dropdownlist.
My expected output is below:
2011 2012 2013 2014
jan 1000 1500 5000 1000
feb 00 00 2000 2000
mar .
. .
. .
dec .
My query is
select
datepart(year, DateOfTransaction),
left(datepart(month, DateOfTransaction), 3),
sum(amount)
from TBL_Transactionmaster
where
datepart(year, DateOfTransaction) = 'input year'
and datepart(month, DateOfTransaction) = 'input month'
Try this query .
For Static Pivot
SELECT *
FROM (
SELECT
left(datename(month,DateOfTransaction),3)as [month], year(DateOfTransaction) as [year]
, Amount
FROM TBL_Transactionmaster
) as s
PIVOT
(
SUM(Amount)
FOR [Year] in([2011],[2012],[2013],[2014],[2015])
)AS piv
For Dynamic Pivot
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(year(DateOfTransaction))
from TBL_Transactionmaster
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT [Month],' + #cols + ' from
(
SELECT
left(datename(month,DateOfTransaction),3)as [month], year(DateOfTransaction) as [year]
, Amount
FROM TBL_Transactionmaster
) x
pivot
(
sum(amount)
for [year] in (' + #cols + ')
) p '
execute(#query)
**For All Month and Replace Null with 0 **
SELECT [month], Isnull([2011],0) as [2011] , ISnull([2012],0) as [2012] ,ISNULL ([2013],0) as [2013] , ISNULL([2014],0) as [2014] , ISNULL([2015],0) as [2015]
FROM (
SELECT
left(datename(month,DateOfTransaction),3)as [month], Amount, year(DateOfTransaction) as [year]
FROM TBL_Transactionmaster
UNION ALL
select [MONTH], Amount, [year] FROM
(Select 'Jan' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Feb' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Mar' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Apr' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'May' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Jun' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Jul' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Aug' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Sep' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Oct' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Nov' as [Month] , 0 as Amount, year(Getdate()) as [year] Union ALL
Select 'Dec' as [Month] , 0 as Amount, year(Getdate()) as [year] ) MN
) as s
PIVOT
(
SUM(Amount)
FOR [Year] in([2011],[2012],[2013],[2014],[2015])
)AS piv
You can use a query like this:
SELECT DATENAME(MONTH, DateOfTransaction) As [Month]
, SUM(CASE WHEN DATEPART(YEAR, DateOfTransaction) = 2011 THEN amount ELSE 0 END) AS [2011]
, SUM(CASE WHEN DATEPART(YEAR, DateOfTransaction) = 2012 THEN amount ELSE 0 END) AS [2012]
, SUM(CASE WHEN DATEPART(YEAR, DateOfTransaction) = 2013 THEN amount ELSE 0 END) AS [2013]
, SUM(CASE WHEN DATEPART(YEAR, DateOfTransaction) = 2014 THEN amount ELSE 0 END) AS [2014]
FROM TBL_Transactionmaster
GROUP BY DATENAME(MONTH, DateOfTransaction), DATEPART(MONTH, DateOfTransaction)
ORDER BY DATEPART(MONTH, DateOfTransaction)
You can use Dynamic SQL like this:
DECLARE #sql nvarchar(max);
SELECT #sql = ISNULL(#sql, 'DATENAME(MONTH, DateOfTransaction) As [Month]') + ', SUM(CASE WHEN DATEPART(YEAR, DateOfTransaction) = ' +
CAST(DATEPART(YEAR, DateOfTransaction) AS VARCHAR(5)) + ' THEN amount ELSE 0 END) AS [' + CAST(DATEPART(YEAR, DateOfTransaction) AS varchar(5)) + ']'
FROM TBL_Transactionmaster
GROUP BY DATEPART(YEAR, DateOfTransaction)
ORDER BY DATEPART(YEAR, DateOfTransaction);
SET #sql = 'SELECT ' + #sql + ' FROM TBL_Transactionmaster GROUP BY DATENAME(MONTH, DateOfTransaction), DATEPART(MONTH, DateOfTransaction) ORDER BY DATEPART(MONTH, DateOfTransaction)';
EXEC(#sql);

Without PIVOT, display data where GROUP BY column are the column names

I have data that looks like the following:
Name Date Hr Min Amt
Joe 20150320 08 00 5
Joe 20150320 08 15 3
Carl 20150320 09 30 1
Carl 20150320 09 45 2
Ray 20150320 13 00 8
Ray 20150320 13 30 6
A simple GROUP BY [Name], [Date], [Hr] would display the total by hour for each salesman.
Without using PIVOT or dynamic sql, how can I display this data where the hours are the columns? With PIVOT I would need to detail each hour, so if the data above were the only data, there would be 3 columns with data (8, 9, 13), and 21 empty columns.
The reason I want to do this is because I would like to create an SSRS report where the columns are the hours. Unfortunately, I can't use a matrix because I can't sort by the column detail (ie. click on "8" and display from smallest to largest); I've already confirmed this limitation with an MS expert.
So any help is appreciated. We have Sql Server 2008 R2.
Thanks.
Select Name
,[Date]
,SUM(Case When Hr = '00' THEN Amt END) [00]
,SUM(Case When Hr = '01' THEN Amt END) [01]
,SUM(Case When Hr = '02' THEN Amt END) [02]
,SUM(Case When Hr = '03' THEN Amt END) [03]
,SUM(Case When Hr = '04' THEN Amt END) [04]
,SUM(Case When Hr = '05' THEN Amt END) [05]
,SUM(Case When Hr = '06' THEN Amt END) [06]
,SUM(Case When Hr = '07' THEN Amt END) [07]
,SUM(Case When Hr = '08' THEN Amt END) [08]
,SUM(Case When Hr = '09' THEN Amt END) [09]
,SUM(Case When Hr = '10' THEN Amt END) [10]
,SUM(Case When Hr = '11' THEN Amt END) [11]
,SUM(Case When Hr = '12' THEN Amt END) [12]
,SUM(Case When Hr = '13' THEN Amt END) [13]
,SUM(Case When Hr = '14' THEN Amt END) [14]
,SUM(Case When Hr = '15' THEN Amt END) [15]
,SUM(Case When Hr = '16' THEN Amt END) [16]
,SUM(Case When Hr = '17' THEN Amt END) [17]
,SUM(Case When Hr = '18' THEN Amt END) [18]
,SUM(Case When Hr = '19' THEN Amt END) [19]
,SUM(Case When Hr = '20' THEN Amt END) [20]
,SUM(Case When Hr = '21' THEN Amt END) [21]
,SUM(Case When Hr = '22' THEN Amt END) [22]
,SUM(Case When Hr = '23' THEN Amt END) [23]
From TablenName
Group By Name ,[Date]
something like this work?? put your key fields into temp tables dont join them so you create a possibility for everything then sub query your amt in.
select * into #Temp1 from (
select '01' as 'Pivot_Hour'
union all
select '02' as 'Pivot_Hour'
union all
select '03' as 'Pivot_Hour'
union all
select '04' as 'Pivot_Hour'
union all
select '05' as 'Pivot_Hour'
--Put all 24 hours in....
)
x
select * into #Temp2 from (
select 'Carl' as 'User'
union all
select 'Joe' as 'User'
union all
select 'Ray' as 'User'
union all
select 'Dave' as 'User'
union all
select 'Seve' as 'User'
---Could select distinct from your data...
)
x
Select * into #Temp3 from (
select '20150321' as 'Date'
union all
select '20150322' as 'Date'
union all
select '20150323' as 'Date'
union all
select '20150324' as 'Date'
union all
select '20150325' as 'Date'
---Could select distinct from your data...
)
x
select *
,(select sum(yrd.amt) from Yourdata Yrd
where yrd.Name = t2.User
and yrd.date = t3.date
and yrd.Hr = t1.Pivot_Hour)Amt
from #Temp1 t1,#Temp2 t2,#Temp3 t3
drop table #Temp1
drop table #Temp2
drop table #Temp3