I need help here. I would like to merge the output of a pivot into a single column if the column name is numeric.
The output content should be like this:
Employeeno Names otherdeduction
xxxxxxxxx james 249-14000, 250-21000, 133-45000
where "249", "250", "133" are column names derived from pivot query. See my code below:
DECLARE #cols nvarchar(MAX)
SELECT #cols = stuff((
SELECT ',' + quotename(COSTITEM_DED_CODE) FROM temp
GROUP BY COSTITEM_DED_CODE ORDER BY COSTITEM_DED_CODE FOR xml path(''), TYPE
).value('.', 'nvarchar(max)')
,1,1,'')
/*****Create a new row at the bottom as a vertical total*******/
DECLARE #vert_total nvarchar(MAX)
SELECT #vert_total = stuff((
SELECT ',sum(' + quotename(COSTITEM_DED_CODE) + ')'
FROM temp
GROUP BY COSTITEM_DED_CODE
ORDER BY COSTITEM_DED_CODE
FOR xml path(''), TYPE
).value('.', 'nvarchar(max)')
,1,1,'')
/***** Create a new column at the end as a horizontal total. ******/
DECLARE #horiz_total nvarchar(MAX)
SELECT #horiz_total = stuff((
SELECT '+isnull(' + quotename(COSTITEM_DED_CODE) + ',0)'
FROM temp
GROUP BY COSTITEM_DED_CODE
ORDER BY COSTITEM_DED_CODE
FOR xml path(''), TYPE
).value('.', 'nvarchar(max)')
,1,1,'')
/***** Avoid NULL in the output by converting all NULLs to 0.*****/
DECLARE #isnulls nvarchar(MAX)
SELECT #isnulls = stuff((
SELECT ',isnull(' + quotename(COSTITEM_DED_CODE) + ',0) as '+quotename(COSTITEM_DED_CODE)
FROM temp
GROUP BY COSTITEM_DED_CODE
ORDER BY COSTITEM_DED_CODE
FOR xml path(''), TYPE
).value('.', 'nvarchar(max)')
,1,1,'')
/***** Generate the pivot, saving the result to a new temporary table*******/
DECLARE #query nvarchar(MAX)
SET #query = 'select SNO,EMPLOYEENO,AFFORDABLE,NAMES,DOB,ACNTNO,AGE,MAXLOANTERM,MAXLOANTERM2,OTHERDEDUCT,' + #cols + ',' + #horiz_total + ' as TOTAL
into temp2
from (select SNO, EMPLOYEENO, AFFORDABLE, NAMES, DOB, ACNTNO, AGE, MAXLOANTERM, MAXLOANTERM2, OTHERDEDUCT, COSTITEM_DED_CODE, INCOMEAMOUNT from temp) x
pivot (sum(incomeamount) for COSTITEM_DED_CODE in (' + #cols + ')) p
select EMPLOYEENO as EMPLOYEENO, '+#isnulls+', isnull(Total,0) as Total
from temp2
union all
select ''TOTAL'', '+#vert_total+',sum(Total)
from temp2'
EXECUTE(#query)
Related
I have created a dynamic pivot and my table has two same dates with diff values ..
i m facing an error when try the pivot
Error : the column 'JUN-2015' was specified multiple times for 'P'
...........................................................
CREATE TABLE #REVENUE
(
ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
[MONTH] VARCHAR(8) NOT NULL,
SALES DECIMAL(8,2) NOT NULL
)
INSERT INTO #REVENUE
([MONTH],SALES)
VALUES
('JAN-2015', 200000.16),
('FEB-2015', 220000.17),
('MAR-2015', 227000.55),
('APR-2015', 247032.75),
('MAY-2015', 287652.75),
('JUN-2015', 265756.75),
('JUN-2015', 265756.75)
DECLARE #cols AS NVARCHAR(MAX) ,
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ',' + QUOTENAME([MONTH])
FROM #REVENUE
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SELECT #query =
'SELECT * FROM
(SELECT
[MONTH],
SALES
FROM #REVENUE)X
PIVOT
(
AVG(SALES)
for [MONTH] in (' + #cols + ')
) P'
EXEC SP_EXECUTESQL #query
If you select #cols you'll see the issue
Please use DISTINCT to avoid the situation:
SELECT #cols = STUFF((SELECT DISTINCT ',' + QUOTENAME([MONTH])
FROM #REVENUE
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
I have a requirement of creating a view for pivot table
This is my source table
According to my requirement I have created the following pivot table
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(Date)
from Salse_Data
group by Date
order by Date
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Product,' + #cols + ' from
(
select Product, Date, Salse
from Salse_Data
) x
pivot
(
sum(Salse)
for Date in (' + #cols + ')
) p '
execute(#query);
Output is
I need to create an indexed view(Materialized View) above query
So i used procedure to create the view
CREATE PROCEDURE [dbo].[ProductSalse_By_Year_Proc_4]
AS
BEGIN
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(Date)
from Salse_Data
group by Date
order by Date
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'CREATE VIEW abcd with schemabinding as SELECT Product,' + #cols + ' from
(
select Product, Date, Salse
from Salse_Data
) x
pivot
(
sum(Salse)
for Date in (' + #cols + ')
) p '
EXECUTE(#query)
END
GO
this execuce without errors but not created the view.
Could you please help on this issue?
I want to use dynamic multiple pivot for my table. I successfully to pivot the table but the problem is there are a lot of NULL values.
This is my current result
And this is what I have tried:
CREATE table #tempdata(
Name Varchar(100),
date date,
MeterSN Varchar(100),
Reading float,
Usage VARCHAR(20),
UsageValue float,
RecordedBy Varchar(100),
Remark Varchar(100)
)
INSERT INTO #tempdata
SELECT c.Name, a.date, b.MeterSN, a.Reading, c.Name + ' Usage' AS Usage,
Reading - LAG(reading) over(partition By currentMeterSNID order by a.date) as UsageValue,
a.RecordedBy, a.Remark
FROM INF_Facility_ElectricalRecord a
INNER JOIN INF_Facility_ElectricalMeter b ON b.id = a.currentMeterSNID
INNER JOIN INF_Facility_Location c ON c.id = b.LocationID
WHERE a.date BETWEEN '2019-03-19' AND '2019-03-20'
ORDER BY c.Name, a.date, b.MeterSN
DECLARE #cols AS NVARCHAR(MAX),
#cols2 AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ',' + QUOTENAME(Name)
from #tempdata
group by Name
order by Name
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SELECT #cols2 = STUFF((SELECT ',' + QUOTENAME(Usage)
from #tempdata
group by Usage
order by Usage
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT CONVERT(VARCHAR(10),date,120) AS Date,' + #cols + ','+ #cols2 + ', recordedby AS [Recorded By] , remark AS Remark from
(
select name,date, Reading, Usage, UsageValue, remark, RecordedBy
from #tempdata
) x
pivot
(
MAX(Reading)
for Name in (' + #cols + ')
) p
pivot
(
MAX(UsageValue)
for Usage in (' + #cols2 + ')
) p
ORDER by date '
execute(#query);
drop table #tempdata
Is there any solution for my problem?
Columns are not alphabetic because I can't use "order by" with "distinct".Please help me...
My Query :
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',MAX(CASE WHEN KullaniciAdi = ''' + p.KullaniciAdi + ''' THEN KisiAdi END) AS ' + QUOTENAME(p.KullaniciAdi)
FROM Populer p FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
set #query = 'SELECT top 100 ' + #cols + ' FROM ( SELECT KullaniciAdi,KisiAdi,ROW_NUMBER() OVER (PARTITION BY KullaniciAdi ORDER BY EklenmeTarihi) AS RowNum FROM Populer ) x GROUP BY RowNum '
EXECUTE(#query)
Results:
Of course you can. The key is to replace the distinct with group by. Then use order by:
SET #cols = STUFF((SELECT ', MAX(CASE WHEN KullaniciAdi = ''' + p.KullaniciAdi + ''' THEN KisiAdi END) AS ' + QUOTENAME(p.KullaniciAdi)
FROM Populer p
GROUP BY KullaniciAdi
ORDER BY p.KullaniciAdi
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'
), 1, 1, ''
) ;
One way around this is to make your query a derived table:
SELECT * FROM
(SELECT DISTINCT {the rest of your current query}) t
ORDER BY SomeColumn
Is it possible to exclude some vaules from the PIVOT results.
Referencing this question i would like to know if it is posible to exclude the columns in the Pivot table that has 0 value.
Imagine there is a count of 0 for EventType Meeting, is it possible not to show it at all?
i hope you have implemented following solution from the question
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(EventType)
from dbo.testTable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT year,' + #cols + '
from
(
select EventType,
year = year(date)
from dbo.testTable
) x
pivot
(
count(EventType)
for EventType in (' + #cols + ')
) p '
execute(#query)
if so then you can do following
DECLARE #cols AS NVARCHAR(MAX),
#where AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(EventType)
from dbo.testTable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select #where = ' where ' + STUFF((SELECT distinct ' Or ' + QUOTENAME(EventType) + ' <> 0 '
from dbo.testTable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,2,3,'')
set #query = 'SELECT year,' + #cols + '
from
(
select EventType,
year = year(date)
from dbo.testTable
) x
pivot
(
count(EventType)
for EventType in (' + #cols + ')
) p ' + #where
execute(#query)