The column 'JUN-2015' was specified multiple times for 'P' - sql-server

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,'')

Related

Create indexed view from defined pivot table

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?

Remove Null Value in Multiple Dynamic Pivot Result

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?

Merging Multiple Columns into a single Column and comma

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)

How to filter pivot results

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)

Generate dynamic columns using pivot

I have the following query which is always giving the error. Could some body help me
to resolve this?
"Incorrect syntax near the keyword '#stqsql'".
My code is:
declare #strsql nvarchar(max)
set #strsql=select merchantid from employee
select *
from
(
Select s.employeeid,
COUNT(*) as TotCount
from Employee s
GROUP BY s.employeeid
)as a
pivot (avg(TotCount) for employeeid IN ('+#stqsql+')) AS NoOfRec
Unfortunately the way you are trying to get dynamic columns does not work. You will have to use something similar to the following:
DECLARE #colsPivot AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
-- this gets the list of values that you want to pivot
select #colsPivot = STUFF((SELECT distinct ', ' + QUOTENAME(merchantid )
from employee
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
-- since you are use a dynamic list you have to use dynamic sql
set #query = 'SELECT ' + #colsPivot + ' from
(
SELECT s.employeeid,
COUNT(*) as TotCount
FROM Employee s
GROUP BY s.employeeid
) src
pivot
(
avg(TotCount)
for employeeid in (' + #colsPivot + ')
) p '
execute(#query)

Resources