I have developed stored procedure as below. I would like to exclude the rows where in each inputdate colum value is null (if there is one input date which is not null, the row should stay). I have no idea how to do that. I serched the web but without any result. Appreciate Your help. Thanks.
create procedure [dbo].[sp_select_staff_time_inputs]
#startDate date,
#enddate date,
#teamid int,
#functionid int,
#servicefunctionid int
as
-- create variables, #columns = inputdates (columns of pivoted table)
DECLARE #columns NVARCHAR(2000)
declare #query nvarchar(4000)
select distinct inputdate into #temp_table_input_dates
from timeinputs
where inputdate >= #startDate and inputdate <= #enddate
order by inputdate
--select * from #temp_table_input_dates
select #columns = isnull(#columns + ',', '') + '[' + convert(varchar,convert(date,inputdate)) + ']' FROM #temp_table_input_dates
--select #columns
create table #temp_table_joins (
soeid varchar(7),
firstname varchar(50),
lastname varchar(50),
teamid int,
team varchar(50),
functionid int,
function varchar(50),
inputdate date,
noofhours float,
servicefunctionid int,
servicefunction varchar(50),
servicephaseid int,
servicephase varchar(50)
)
insert into #temp_table_joins
--select * into #temp_table_joins from
SELECT
u.SOEID, u.Firstname, u.Lastname, u.teamid,
t.team, t.functionid,
f.function,
ti.inputdate, ti.noofhours, ti.servicefunctionid,
sf.servicefunction, sf.servicephaseid,
sp. servicephase
from users u
inner join teams t on u.teamid = t.teamid
inner join functions f on t.functionid = f.functionid
inner join timeinputs ti on u.userid = ti.userid
inner join servicefunctions sf on ti.servicefunctionid = sf.servicefunctionid
inner join servicephases sp on sf.servicephaseid = sp.servicephaseid
--select * from #temp_table_joins
set #query = 'select soeid, firstname, lastname, teamid, team, functionid,
function, servicefunctionid, servicefunction, servicephaseid,
servicephase' + #columns + ' from
(select * from #temp_table_joins
) p
pivot (sum (noofhours) for inputdate in (' + #columns + ')) as asd'
--select #query
--select *, noofhours, userid from timeinputs
execute(#query)
drop table #temp_table_joins
drop table #temp_table_input_dates
GO
I'm not sure, but
DECLARE #columnscondition NVARCHAR(2000)
...
SELECT #columnscondition = isnull(#columns + ' AND ', ' WHERE ') + convert(varchar,convert(date,inputdate)) + ' IS NOT NULL ' FROM #temp_table_input_dates
...
set #query = 'select soeid, firstname, lastname, teamid, team, functionid,
function, servicefunctionid, servicefunction, servicephaseid,
servicephase' + #columns + ' from
(select * from #temp_table_joins
) p'
+ #columnscondition +
'pivot (sum (noofhours) for inputdate in (' + #columns + ')) as asd'
Perhaps, parentheses are missing in the dynamic part.
Thank You valiik.
Your solltion doesn't wok to me as expected but You inspired me to create my own.
Please see below code:
create procedure [dbo].[sp_select_staff_time_inputs]
#startDate date,
#enddate date,
#gvoteamid int,
#gvofunctionid int,
#servicefunctionid int
as
-- create variables, #columns = inputdates (columns of pivoted table)
DECLARE #columns NVARCHAR(2000)
declare #query nvarchar(4000)
DECLARE #columnscondition NVARCHAR(2000)
select distinct inputdate into #temp_table_input_dates
from timeinputs
where inputdate >= #startDate and inputdate <= #enddate
order by inputdate
--select * from #temp_table_input_dates
select #columns = isnull(#columns + ',', '') + '[' + convert(varchar,convert(date,inputdate)) + ']' FROM #temp_table_input_dates
select #columnscondition = isnull(#columnscondition + ' and ', '') + '[' + convert(varchar,convert(date,inputdate)) + '] is not null' FROM #temp_table_input_dates
--SELECT #columnscondition
--select #columns
create table #temp_table_joins (
soeid varchar(7),
firstname varchar(50),
lastname varchar(50),
gvoteamid int,
gvoteam varchar(50),
gvofunctionid int,
gvofunction varchar(50),
inputdate date,
noofhours float,
servicefunctionid int,
servicefunction varchar(50),
servicephaseid int,
servicephase varchar(50)
)
insert into #temp_table_joins
--select * into #temp_table_joins from
SELECT
u.SOEID, u.Firstname, u.Lastname, u.gvoteamid,
t.gvoteam, t.gvofunctionid,
f.gvofunction,
ti.inputdate, ti.noofhours, ti.servicefunctionid,
sf.servicefunction, sf.servicephaseid,
sp. servicephase
from users u
inner join gvoteams t on u.gvoteamid = t.gvoteamid
inner join gvofunctions f on t.gvofunctionid = f.gvofunctionid
inner join timeinputs ti on u.userid = ti.userid
inner join servicefunctions sf on ti.servicefunctionid = sf.servicefunctionid
inner join servicephases sp on sf.servicephaseid = sp.servicephaseid
--select * from #temp_table_joins
set #query = 'select soeid, firstname, lastname, gvoteamid, gvoteam, gvofunctionid,
gvofunction, servicefunctionid, servicefunction, servicephaseid,
servicephase, ' + #columns + ' from
(select * from #temp_table_joins where noofhours is not null
) p
pivot (sum (noofhours) for inputdate in (' + #columns + ')) as asd
where (' + #columnscondition +')'
--select #query
--select #query
--select *, noofhours, userid from timeinputs
execute(#query)
drop table #temp_table_joins
drop table #temp_table_input_dates
GO
Related
Sorry if this isn't the best way to ask this but I am stuck at this point, I have tried researching but to no avail, trying to join these two queries:
SELECT [id]
,[title]
,[desc]
FROM [localTest].[dbo].[main];
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) from [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT [ID], ' + #cols + ' from (select [ID], [Year], [Amount] FROM [localTest].[dbo].[Years] ) x pivot (min([Amount]) for [Year] in (' + #cols + ')) p '
execute(#query);
Looking for the final result here:
enter image description here
I figured it out, here is my solution:
DECLARE #cols AS NVARCHAR(MAX);
SELECT #cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) FROM [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'');
DECLARE #Sql VARCHAR(max);
SELECT #Sql = 'SELECT * FROM [localTest].[dbo].[main] a join (
SELECT * FROM (
SELECT [ID] id, [Year], [Amount]
FROM [localTest].[dbo].[Years]
) x pivot (
min([Amount])
for [Year] IN ('+#cols+')
) p ) as b on a.[ID] = b.id';
EXECUTE(#Sql);
Insert the result of second query to a #temp table and join the #temp table to main table like below:
SELECT [id]
,[title]
,[desc]
FROM [localTest].[dbo].[main];
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) from [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT [ID], ' + #cols + ' from (select [ID], [Year], [Amount] FROM [localTest].[dbo].[Years] ) x pivot (min([Amount]) for [Year] in (' + #cols + ')) p '
insert into #temp
execute(#query);
select * from [localTest].[dbo].[main] AS a inner join #temp as b on a.id = b.id
How can I convert rows into columns and create different name for each column?
create table #TempTable (InvoiceNum int,State varchar(2), ChargeName varchar(50), PercentageRate decimal(5,3), FlatRate decimal(5,2))
insert into #TempTable values (235736, 'AZ','Inspection & Policy Fee', NULL,250.00)
,(235736, 'AZ','Surplus Line Tax',0.03,NULL)
,(235736, 'AZ','Stamping Fee',0.002,NULL
)
I need something like that:
UPDATE:
Using example I was able to unpivot it but the result is not what I wanted to:
create table #TempTable (InvoiceNum int,State varchar(2), ChargeName varchar(50), PercentageRate decimal(5,3), FlatRate decimal(5,2))
insert into #TempTable values (235736, 'AZ','Inspection & Policy Fee', NULL,250.00)
,(235736, 'AZ','Surplus Line Tax',0.03,NULL)
,(235736, 'AZ','Stamping Fee',0.002,NULL)
--select * from #TempTable
Declare #SQL nvarchar(max),
#query nvarchar(max)
select #SQL = STUFF((SELECT ',' + QUOTENAME(ChargeName)
from #TempTable
group by ChargeName, InvoiceNum
order by InvoiceNum
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--select #SQL
set #SQL = 'SELECT ' + #SQL + ' from
(
select PercentageRate, ChargeName
from #TempTable
) x
pivot
(
max(PercentageRate)
for ChargeName in (' + #SQL + ')
) p '
exec sp_executesql #SQL;
UPDATE:
Running below query gives me this:
Why ChargeName is not on the first row? I would expect to see it like this: What am I missing?
declare #TempTable table (InvoiceNum int,StateID varchar(2), ChargeName varchar(50), PercentageRate decimal(5,3), FlatRate decimal(5,2))
insert into #TempTable values (235736, 'AZ','Inspection & Policy Fee', NULL,250.00)
,(235736, 'AZ','Surplus Line Tax',0.03,NULL)
,(235736, 'AZ','Stamping Fee',0.002,NULL)
select
InvoiceNum,
ChargeName,
StateID,
PercentageRate,
FlatRate,
row_number() over (partition by InvoiceNum order by ChargeName) as RN
into #TempTable
from #TempTable #TempTable
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(RN)
FROM (SELECT DISTINCT RN FROM #TempTable) AS RN
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT InvoiceNum, ' + #ColumnName + '
FROM #TempTable
PIVOT(MAX(ChargeName)
FOR RN IN (' + #ColumnName + ')) AS PVTTable'
EXEC sp_executesql #DynamicPivotQuery
drop table #TempTable
I would just join the temp table multiple times as needed.
Given your #TempTable
SELECT T1.InvoiceNum,
Tax1_Jurisdiction = T1.State, Tax1_TaxType = T1.ChargeName, Tax1_Percent = T1.PercentageRate, Tax1_FixedRate = T1.FlatRate,
Tax2_Jurisdiction = T2.State, Tax2_TaxType = T2.ChargeName, Tax2_Percent = T2.PercentageRate, Tax2_FixedRate = T2.FlatRate,
Tax3_Jurisdiction = T3.State, Tax3_TaxType = T3.ChargeName, Tax3_Percent = T3.PercentageRate, Tax3_FixedRate = T3.FlatRate
FROM #TempTable T1
JOIN #TempTable T2 ON T1.InvoiceNum = T2.InvoiceNum
JOIN #TempTable T3 ON T1.InvoiceNum = T3.InvoiceNum
WHERE T1.ChargeName = 'Inspection & Policy Fee'
AND T2.ChargeName = 'Surplus Line Tax'
AND T3.ChargeName = 'Stamping Fee'
;
In this stored procedure, I have to use
SELECT *
FROM #policyData a
LEFT OUTER JOIN ##Temp b ON b.qguid = a.quoteguid
LEFT OUTER JOIN ##Temp c ON c.qguid = a.quoteguid2;
And because of that I have two columns with the same name "QuoteGuid".
Then when I try to add this query in SSRS, I get an error, because I have 2 columns with the same name.
I am not the author of this stored procedure, so I cannot understand is any chance to eliminate or rename column name that causing this.
CREATE PROCEDURE dbo.SP_Catalytic_WindEQRenewalExtract
#pos INT,
#len INT,
#value varchar(8000),
#PriorDays INT,
#PastDays INT,
#LineName varchar(50)
AS
SET NOCOUNT ON;
SELECT #LineName ='wind'
SELECT #PriorDays= -15
SELECT #PastDays = 55
DECLARE #policyData TABLE
(
NamedInsured varchar(1000),
displaystatus varchar(100),
quoteguid uniqueidentifier,
quoteid int,
controlno int,
ExpirationDate datetime,
MonthName nvarchar(25),
ExpiringPremium money,
Underwriter varchar(250),
linename varchar(25),
RenewalSubmissionRecieved varchar(5),
QuotedPremium money,
quoteguid2 uniqueidentifier,
controlno2 int,
displaystatus2 varchar(50),
quotestatuscomment varchar(2500),
quotestatusreasoncomment varchar(2500),
BoundPremium money,
Underwriter2 varchar(500)
)
INSERT INTO #policyData
EXEC ('Catalytic_sp_FetchRenewalPolicy ' + #PriorDays + ',' + #PastDays + ', ' + #LineName + '')
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SET #cols = STUFF((SELECT ',' + QUOTENAME(c.locationCode)
FROM Catalytic_vw_LocationCodeByLine c WHERE c.linename =#LineName order by c.CompanyName, c.LocationCode
FOR XML PATH('')),1,1,'')
IF OBJECT_ID('tempdb.dbo.##Temp', 'U') IS NOT NULL
DROP TABLE ##Temp;
set #query =
'select * into ##Temp
from
(SELECT QUOTEGUID as qguid, ' + #cols + ' from
(
select QuoteGUID, LocationCode, LineName,LineGUID
--from Catalytic_vw_PolicyLocationCode where quoteguid=''99D60178-C33B-4A3F-9EA7-0001EF31626A''
from Catalytic_vw_PolicyLocationCode
) x
pivot
(
max(locationCode)
for locationCode in (' + #cols + ')
)p)x'
EXEC sp_executesql #query;
set #pos = 0
set #len = 0
WHILE CHARINDEX(',', #cols, #pos+1)>0
BEGIN
set #len = CHARINDEX(',', #cols, #pos+1) - #pos
set #value = SUBSTRING(#cols, #pos, #len)
-- PRINT #value
set #pos = CHARINDEX(',', #cols, #pos+#len) +1
declare #sql nvarchar (1000);
set #sql = N'update ##Temp set ' + #value + '= ''X'' where len(' + #value + ') > 0 ' ;
exec sp_executesql #sql;
END
SELECT *
FROM
#policyData a
LEFT OUTER JOIN ##Temp b on b.qguid = a.quoteguid
/*Because I am using another LEFT JOIN here, I have two columns namem "qguid"*/
LEFT OUTER JOIN ##Temp c on c.qguid = a.quoteguid2;
DROP TABLE ##Temp;
just change where you are trying to make another left join in the last and explicitly mention all column name.
SELECT a.* ,b.*,c.qguid as qguid1
FROM
#policyData a
LEFT OUTER JOIN ##Temp b on b.qguid = a.quoteguid
/*Because I am using another LEFT JOIN here, I have two columns namem "qguid"*/
LEFT OUTER JOIN ##Temp c on c.qguid = a.quoteguid2;
Another way,
declare #CurDate datetime=getdate()
Declare #CurDate1 varchar(8)
select #CurDate1= replace(convert(varchar(8), #CurDate, 112), ':','')
select #CurDate1
SET #cols = STUFF((SELECT ',' + QUOTENAME(c.locationCode) +#CurDate1
FROM Catalytic_vw_LocationCodeByLine c WHERE c.linename =#LineName order by c.CompanyName, c.LocationCode
FOR XML PATH('')),1,1,'')
If I am understanding your question correctly you need to use an existing stored procedure to get data for an SSRS report and you cannot modify the procedure. The problem is the stored procedure returns two columns with the same name and SSRS will not accept that in a dataset.
To get around that call the stored procedure and store its results in a temp table with different column names. Then output the temp table contents. This gives you fill control over the name of the columns. See example below.
CREATE PROCEDURE dbo.sp_Test
AS
BEGIN
SELECT
1 AS 'Test1',
2 AS 'Test2',
3 AS 'Test3',
3 AS 'Test3'
END
CREATE TABLE #Test
(
Test1 int,
Test2 int,
Test3 int,
Test4 int
)
INSERT INTO #Test
EXEC dbo.sp_Test
SELECT * FROM #Test
DROP TABLE #Test
I have two tables MasterTableTest8 and HistoricDatatest8.
create table MasterTableTest8
(ID int primary key, Name varchar(10))
insert into MasterTableTest8 values (1,'ATS')
insert into MasterTableTest8 values (2,'BTS')
CREATE TABLE HistoricDatatest8
(
ID int FOREIGN KEY REFERENCES MasterTableTest8(ID),
Name varchar(100),
ShortName varchar(10),
Reason varchar(10),
Importance varchar(10),
Noofissues int,
inserteddate datetime
)
insert into HistoricDatatest8 values (1,'ATS','S', 'Other','High',26,getdate()-7)
insert into HistoricDatatest8 values (1,'ATS','S', 'Other','High',8,getdate()+7)
insert into HistoricDatatest8 values (1,'ATS','S', 'Other','High',80,getdate())
insert into HistoricDatatest8 values (2,'BTS','S1', 'Other','LOW',26,getdate()-7)
insert into HistoricDatatest8 values (2,'BTS','S1', 'Other','LOW',8,getdate()+7)
insert into HistoricDatatest8 values (2,'BTS','S1', 'Other','LOW',80,getdate())
--Created and inserted two tables.
select
N.ID,
N.Name,
ShortName,
Reason,
Importance,
Noofissues,
inserteddate
INTO #TABLE
FROM HistoricDatatest8 N
JOIN MasterTableTest S ON N.ID=S.ID
--Inserting the required data in the Hash table.
--drop table #table
DECLARE #cols NVARCHAR (MAX)
SELECT #cols = COALESCE (#cols + ',[' + CONVERT(NVARCHAR, [inserteddate], 106) + ']',
'[' + CONVERT(NVARCHAR, [inserteddate], 106) + ']')
FROM (SELECT DISTINCT [inserteddate] FROM #TABLE) PV
ORDER BY [inserteddate]
DECLARE #query NVARCHAR(MAX)
SET #query = '
SELECT * FROM
(
SELECT * FROM #TABLE
) x
PIVOT
(
count(Noofissues)
FOR [inserteddate] IN (' + #cols + ')
) p'
EXEC SP_EXECUTESQL #query
Current Result
Expected Result:
What is your expected result? Your current display shows the same current and expected result.
Are you expecting:
Date | Name | ShortName | Reason | Importance | Number of Issues|
05-Jul-16 | ATS | S| Other| High|26
12-Jul-16|BTS |S1| Other | LOW|80
After lots of R & D i got this result, might be useful to some others. if any optimized answer will be appreciated.
select * from HistoricDatatest80 order by ID
select N.ID,N.Name,ShortName,Reason,Importance,Noofissues,inserteddate INTO #TABLE FROM HistoricDatatest80 N JOIN MasterTableTest80 S ON N.ID=S.ID
--drop table #table
DECLARE #cols NVARCHAR (MAX)
SELECT #cols = COALESCE (#cols +',','')+ '['+DATEValue+']'
FROM (SELECT DISTINCT (CONVERT(NVARCHAR, [inserteddate], 106)) AS DATEValue FROM HistoricDatatest80) PV
ORDER BY DATEValue
print #cols
DECLARE #query NVARCHAR(MAX)
SET #query = '
SELECT * FROM
(
SELECT ShortName,Reason,Importance,Noofissues,(CONVERT(NVARCHAR, [inserteddate], 106)) AS DATEValue FROM #TABLE
) x
PIVOT
(
sum(Noofissues)
FOR [DATEValue] IN (' + #cols + ')
) p'
EXEC SP_EXECUTESQL #query
drop table #table
create PROC [dbo].[Sample]
#fromDate datetime, #toDate datetime, #office varchar(30)
AS
declare #char varchar(200)
DECLARE #Temp TABLE (ID int, Name varchar(50), Countt int, Reason varchar(20))
INSERT INTo #Temp (ID, Name, Countt, Reason)
SELECT DD.ID, O.Name, Count(DD.Reason) Countt, convert(varchar,DD.Reason) Reason FROM samp1 AS DD
INNER JOIN samp3 AS O ON O.ID = DD.ID
select #char = coalesce(#char + ',', '') + reason from #Temp
select *
FROM
(
select distinct ID, Name, Reason, sum(Countt) as Countt from #Temp group by Name, Reason, ID
)P
PIVOT
(
SUM(Countt)
FOR Reason
IN (select #char)
) AS pvt
Error: Msg 156, Level 15, State 1, Procedure Sample, Line 45
Incorrect syntax near the keyword 'select'.
can anybody help me
SELECT #char = COALESCE(#char + ',[' + reason + ']', '[' + reason + ']')
FROM #Temp
DECLARE #pvtQuery VARCHAR(2500)
SET #pvtQuery =
'
SELECT ID, Name, ' + #char + '
FROM
(
SELECT DISTINCT ID, Name, Reason, SUM(Countt) AS Countt
FROM #Temp
GROUP BY Name, Reason, ID
) P
PIVOT
(
SUM(Countt)
FOR Reason
IN (' + #char + ')
) AS pvt
'
EXEC (#pvtQuery)