Store procedure for a select statement which should take input - sql

Can anyone please help me with the store procedure for the following
select statement which should take an input of completeddatekey which
is at the bottom of the select statement
CompletedDateKey is filled with a key in this code but I need a store procedure that should take an input of completeddatekey
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = '20140131'
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null

Its really simple. Just create procedure like below
create procedure MyProc(
#CompletedDateKey varchar(20) )
as
Begin
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = #CompletedDateKey
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
End
Execute it like
Execute MyProc '20140131'

Related

SQL - Pivot Column data to raw. Not as table header value

Here is my current output format:
This is the output I need:
And here is my code
SELECT
tblPO.PONO,
CONVERT(CHAR(10), tblPO.POEnterdDate, 126) AS PODate,
tblSupplier.SupplierCode + '-' + tblSupplier.SupName AS SupplierName,
tblPOMaterials.MaterialCode + '-' + tblMaterial.MaterialDescription AS [Item Description],
tblPR.PRType AS [SPR or PR],
tblPOFromPR.PRNO AS [PR/SPR],
tblUnit.UnitCode,
tblPOMaterials.POQty AS Qty,
tblPOMaterials.UnitPrice,
tblPOMaterials.POQty * tblPOMaterials.UnitPrice AS [Total Price]
FROM
tblPO
INNER JOIN
tblPOMaterials ON tblPO.PONO = tblPOMaterials.PONO
INNER JOIN
tblMaterial ON tblPOMaterials.MaterialCode = tblMaterial.MaterialCode
INNER JOIN
tblSupplier ON tblPO.POSupplierID = tblSupplier.SupplierID
INNER JOIN
tblPOFromPR ON tblPO.PONO = tblPOFromPR.PONO
AND tblPOMaterials.MaterialCode = tblPOFromPR.MaterialCode
INNER JOIN
tblUnit ON tblMaterial.UnitID = tblUnit.UnitID
INNER JOIN
tblPR ON tblPOFromPR.PRNO = tblPR.PRNO
WHERE
(CONVERT(date, tblPO.PODate) BETWEEN #StartDate AND #EndDate)
AND (tblPO.POType <> 'Service')
AND (tblPO.POType = #Category)
ORDER BY
tblPO.PONO
Try Using Stuff and Distinct
SELECT DISTINCT tblPO.PONO, CONVERT(CHAR(10), tblPO.POEnterdDate, 126) AS PODate, tblSupplier.SupplierCode + '-' + tblSupplier.SupName AS SupplierName,
tblPOMaterials.MaterialCode + '-' + tblMaterial.MaterialDescription AS [Item Description], tblPR.PRType AS [SPR or PR],
STUFF((
SELECT '/' + CAST(T.PRNO AS VARCHAR(100))
FROM dbo.tblPOFromPR T
WHERE tblPO.PONO = T.PONO AND tblPOMaterials.MaterialCode = T.MaterialCode
FOR XML PATH('')),1,1,'') AS [PR/SPR],
tblUnit.UnitCode, tblPOMaterials.POQty AS Qty, tblPOMaterials.UnitPrice,
tblPOMaterials.POQty * tblPOMaterials.UnitPrice AS [Total Price]
FROM tblPO INNER JOIN tblPOMaterials ON tblPO.PONO = tblPOMaterials.PONO
INNER JOIN tblMaterial ON tblPOMaterials.MaterialCode = tblMaterial.MaterialCode
INNER JOIN tblSupplier ON tblPO.POSupplierID = tblSupplier.SupplierID
INNER JOIN tblPOFromPR ON tblPO.PONO = tblPOFromPR.PONO AND tblPOMaterials.MaterialCode = tblPOFromPR.MaterialCode
INNER JOIN tblUnit ON tblMaterial.UnitID = tblUnit.UnitID
INNER JOIN tblPR ON tblPOFromPR.PRNO = tblPR.PRNO
WHERE (CONVERT(date, tblPO.PODate) BETWEEN #StartDate AND #EndDate) AND (tblPO.POType <> 'Service') AND (tblPO.POType = #Category)
ORDER BY tblPO.PONO

Get results only if it exists in a union tsql

So I have the following select that will output datametrics and I have a Union as well
SELECT DISTINCT (SELECT DATEADD(DAY,-1,DATEADD(MONTH,DATEDIFF(MONTH,0,MAX(GreatestDate)) + 1, 0))
FROM
(VALUES (max(th.TransactionEffectiveDt)),(max(bp.EffectiveDt)),(max(th.TransactionDt))) AS Value(GreatestDate)) AS BookDate
,th.Transactioncd TransactionType
,bp.PolicyNumber PolicyNumber
,cast(bp.EffectiveDt AS DATE) EffectiveDate
,max(cast(th.TransactionEffectiveDt AS DATE)) TransactionEffectiveDate
,NULL
,th.TransactionNumber TransactionNumber
,cast(bp.ExpirationDt AS DATE) ExpirationDate
,replace(UPPER(ni.IndexName), ',', '') InsuredName
,replace(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''), ',', '') InsuredStreetAddress
,UPPER(ad.City) InsuredCity
,UPPER(ad.StateProvCd) InsuredState
,ad.PostalCode InsuredZipCode
,i.EntityTypeCd InsuredType
,isnull(tr.ReasonCd, '') ReasonCode
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4)) ProrateFactor
,'0'
,'0'
,'0'
,bd.YearBuilt YrConstruction
,ln.PROPDed + '%' [% loss ded EQ]
,CAST(bd.BldgNumber AS VARCHAR(255)) BldgNumber
,CONVERT(INT,REPLACE(bd.BuildingValue,',','')) BuildingValue
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',','')) ContentsBLimit
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',','')) ContentsCLimit
,CONVERT(INT,REPLACE(bd.TIBLimit,',','')) TIBLimit
,CONVERT(INT,REPLACE(bd.BILimit,',','')) BILimit
,CONVERT(INT,REPLACE(bd.EDPLimit,',','')) EDPLimit
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.risk r on r.SystemId=bp.SystemId
AND r.CMMContainer=bp.CMMContainer
AND r.ParentId=ln.Id
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
AND bd.ParentId=r.id
AND bd.[Status] = 'ACTIVE'
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd in ('RiskAddr')
AND ad.ParentId = bd.id
INNER JOIN java.transactioninfo th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'Application'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC'
AND th.TransactionNumber in (select distinct th.TransactionNumber
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd = 'InsuredMailingAddr'
INNER JOIN java.transactionhistory th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'policy'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC')
GROUP BY
th.Transactioncd
,bp.PolicyNumber
,cast(bp.EffectiveDt AS DATE)
,th.TransactionNumber
,cast(bp.ExpirationDt AS DATE)
,UPPER(ni.IndexName)
,isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), '')
,UPPER(ad.City)
,UPPER(ad.StateProvCd)
,ad.PostalCode
,i.EntityTypeCd
,isnull(tr.ReasonCd, '')
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4))
,bd.YearBuilt
,ln.PROPDed + '%'
,CAST(bd.BldgNumber AS VARCHAR(255))
,CONVERT(INT,REPLACE(bd.BuildingValue,',',''))
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',',''))
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',',''))
,CONVERT(INT,REPLACE(bd.TIBLimit,',',''))
,CONVERT(INT,REPLACE(bd.BILimit,',',''))
,CONVERT(INT,REPLACE(bd.EDPLimit,',',''))
UNION
SELECT distinct (SELECT DATEADD(DAY,-1,DATEADD(MONTH,DATEDIFF(MONTH,0,MAX(GreatestDate)) + 1, 0))
FROM
(VALUES (max(th.TransactionEffectiveDt)),(max(bp.EffectiveDt)),(max(th.TransactionDt))) AS Value(GreatestDate)) AS BookDate
,th.Transactioncd TransactionType
,bp.PolicyNumber PolicyNumber
,cast(bp.EffectiveDt AS DATE) EffectiveDate
,max(cast(th.TransactionEffectiveDt AS DATE)) TransactionEffectiveDate
,NULL
,th.TransactionNumber TransactionNumber
,cast(bp.ExpirationDt AS DATE) ExpirationDate
,replace(UPPER(ni.IndexName), ',', '') InsuredName
,replace(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''), ',', '') InsuredStreetAddress
,UPPER(ad.City) InsuredCity
,UPPER(ad.StateProvCd) InsuredState
,ad.PostalCode InsuredZipCode
,i.EntityTypeCd InsuredType
,isnull(tr.ReasonCd, '') ReasonCode
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4)) ProrateFactor
,isnull(cast(th.writtenpremiumamt as int), '0') APRP
,isnull(cast(th.inforcepremiumamt as int), '0') AnnualPremium
,CONVERT(INT,REPLACE(REPLACE(REPLACE(ln.DWELLLimit, '.00', ''), '$', ''),',','')) AggreLimit
,'0'
,ln.PROPDed +'%' [% loss ded EQ]
,CASE
WHEN BD.bldgnumber > 0
THEN '0' END as bldgnumber
,'0'
,'0'
,'0'
,'0'
,'0'
,'0'
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd = 'InsuredMailingAddr'
INNER JOIN java.transactionhistory th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'policy'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC'
GROUP BY
th.Transactioncd
,bp.PolicyNumber
,cast(bp.EffectiveDt AS DATE)
,cast(th.TransactionEffectiveDt AS DATE)
,th.TransactionNumber
,cast(bp.ExpirationDt AS DATE)
,UPPER(ni.IndexName)
,(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''))
,UPPER(ad.City)
,UPPER(ad.StateProvCd)
,ad.PostalCode
,i.EntityTypeCd
,isnull(tr.ReasonCd, '')
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4))
,isnull(cast(th.writtenpremiumamt as int), '0')
,isnull(cast(th.inforcepremiumamt as int), '0')
,CONVERT(INT,REPLACE(REPLACE(REPLACE(ln.DWELLLimit, '.00', ''), '$', ''),',',''))
,ln.PROPDed +'%'
,CASE
WHEN BD.bldgnumber > 0
THEN '0' END
ORDER BY PolicyNumber
,transactionnumber
,bldgnumber
,BOOKDATE
I get the following results:
enter image description here
Notice how there are three 1's and three 2's but only two 3's? That's because in my union, the 3 doesn't exist. Only on my top query does. What I want to do is to select everything where only it exists in my union. So for this instance, since 3 doesn't exist in my union, I want to omit it from my results. I tried doing EXISTS and IN but still not getting what I want. Been stuck on this.
Try this approach
;WITH cte
AS (SELECT 1 AS fst_indicator, -- To identify the records from first query
NULL as scd_indicator,
TransactionNumber,..
FROM First_Query
UNION ALL -- Change it to UNION if you really want to remove duplicates
SELECT NULL AS fst_indicator,
1 as scd_indicator,-- To identify the records from second query
TransactionNumber,..
FROM Second_Query),
cte1
AS (SELECT TransactionNumber
FROM cte
GROUP BY TransactionNumber
HAVING Sum(fst_indicator) >= 1 -- to make sure TransactionNumber is present in first query
AND Sum(scd_indicator) >= 1 -- to make sure TransactionNumber is present in second query
)
SELECT *
FROM cte c
WHERE EXISTS (SELECT 1
FROM cte1 c1
WHERE c.TransactionNumber = c1.TransactionNumber)

Get specific columns from xml path

I have this query here:
SELECT
T.AKSIONERET,
sd.Identification_No, sd.Date_Of_Incorp,
sd.Ownership_Desc, sd.Ownership_Code,
sd.Subject_Name_Code, sd.Subject_Name,
sd.Subject_Type_Code,
LEFT(sd.Object_Desc, 3999) AS Object_Desc,
sd.Subject_Status_Name, sd.Subject_Name,
nr2.NACE_Code, nr2.NACE_PARENT, nr2.Description,
sd.Subject_Type_Name, sd.Subject_Status_Name,
sd.Subject_Type_Name, f.Place_Of_Registration, sd.Object_Desc
FROM
NRC_Subject_DEF AS sd
LEFT JOIN
NRC_Nace_REV2 AS nr2 ON nr2.Subject_DEF_Code = sd.Subject_DEF_Code
LEFT JOIN
NRC_ForeignCompany AS f ON sd.ForeignCompany_Code = f.ForeignCompany_Code
LEFT JOIN
(SELECT
SDP.Subject_DEF_Code,
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
FOR XML PATH('')) AS AKSIONERET
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T ON T.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
I need to retrieve, instead of T.AKSIONERET the FullAksionerCitizenship which I get from the for xml path.
I know I have to do some other SELECT but I kept getting errors, syntax errors.
Could someone help?
Thanks in advance
I'm quite sure, that there could be a better design and I'm not able to run this against test data off course, but this could work:
SELECT
T.AKSIONERET,
T2.FullAksionerCitizenship,
sd.Identification_No, sd.Date_Of_Incorp,
sd.Ownership_Desc, sd.Ownership_Code,
sd.Subject_Name_Code, sd.Subject_Name,
sd.Subject_Type_Code,
LEFT(sd.Object_Desc, 3999) AS Object_Desc,
sd.Subject_Status_Name, sd.Subject_Name,
nr2.NACE_Code, nr2.NACE_PARENT, nr2.Description,
sd.Subject_Type_Name, sd.Subject_Status_Name,
sd.Subject_Type_Name, f.Place_Of_Registration, sd.Object_Desc
FROM
NRC_Subject_DEF AS sd
LEFT JOIN
NRC_Nace_REV2 AS nr2 ON nr2.Subject_DEF_Code = sd.Subject_DEF_Code
LEFT JOIN
NRC_ForeignCompany AS f ON sd.ForeignCompany_Code = f.ForeignCompany_Code
LEFT JOIN
(SELECT
SDP.Subject_DEF_Code,
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
FOR XML PATH('')) AS AKSIONERET
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T ON T.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
--here starts the new block (difficult for me without knowing your db...)
LEFT JOIN
(SELECT
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
) AS FullAksionerCitizenship
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T2 ON T2.Subject_DEF_Code = SD.SUBJECT_DEF_CODE

TSQL use inner select result for outer FROM

I have a query that looks like the following:
A.[approvalDate],
A.[locationID],
B.[FirstName] + ' ' + B.[LastName] AS nomineeName,
B.[ntid] AS nomineeNTID,
B.[qid] AS nomineeQID,
B.[GeoLocationDesc] as locationName,
C.[FirstName] + ' ' + C.[LastName] AS submitName,
C.[ntid] AS submitNTID,
C.[empID] submitEmpID,
D.[categoryName],
(
SELECT G.[qid] FROM empowermentProxies AS G WHERE G.[proxy] = #QID
),
E.[FirstName] + ' ' + E.[LastName] as behalfOf,
E.[NTID] AS behalfOfNTID
FROM empowermentSubmissions AS A
INNER JOIN
empTable AS B
ON A.[nomineeQID] = B.[qid]
LEFT OUTER JOIN
empTable AS C
ON A.[subQID] = C.[qid]
INNER JOIN
empowermentCategories AS D
ON A.[categoryID] = D.[catID]
JOIN empTable AS E
ON E.[qid] = G.[qid]
WHERE #QID IN (SELECT proxy FROM empowermentProxies)
AND A.[statusID] = 1
FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');
I am trying to user the result of the inner select G.qid in the join statement but keep getting an error saying G isn't bound.
Is this possible to do? There should only be 1 result returned from the inner select.
Just move it to the from clause:
. . .
D.[categoryName],
Q.g_qid,
. . .
FROM empowermentSubmissions A INNER JOIN
empTable B
ON A.[nomineeQID] = B.[qid] LEFT OUTER JOIN
empTable C
ON A.[subQID] = C.[qid] INNER JOIN
empowermentCategories D
ON A.[categoryID] = D.[catID] CROSS JOIN
(SELECT G.[qid] as g_qid
FROM empowermentProxies G
WHERE G.[proxy] = #QID
) G JOIN
empTable E
ON E.[qid] = G.[qid]
please try below one
A.[approvalDate],
A.[locationID],
B.[FirstName] + ' ' + B.[LastName] AS nomineeName,
B.[ntid] AS nomineeNTID,
B.[qid] AS nomineeQID,
B.[GeoLocationDesc] as locationName,
C.[FirstName] + ' ' + C.[LastName] AS submitName,
C.[ntid] AS submitNTID,
C.[empID] submitEmpID,
D.[categoryName],
sol1.qid,
E.[FirstName] + ' ' + E.[LastName] as behalfOf,
E.[NTID] AS behalfOfNTID
FROM empowermentSubmissions AS A
INNER JOIN
empTable AS B
ON A.[nomineeQID] = B.[qid]
LEFT OUTER JOIN
empTable AS C
ON A.[subQID] = C.[qid]
INNER JOIN
empowermentCategories AS D
ON A.[categoryID] = D.[catID]
JOIN empTable AS E
ON E.[qid] = G.[qid]
left join (SELECT G1.[qid] FROM empowermentProxies AS G1 WHERE G.[proxy] = #QID) sol1
on g.qid=sol1.qid
WHERE #QID IN (SELECT proxy FROM empowermentProxies)
AND A.[statusID] = 1
FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');

Error while using t sql pivot table in SSRS

I have a sql code that runs perfectly on SQL SERVER, it runs fine when I run it in SSRS, but when I substitute my constant value with a variable, it does not return any values.
This is the code I am using.
------LISTADO DE calificaciones de ESTUDIANTES
DECLARE #PivotColumnHeaders VARCHAR(MAX)
SELECT #PivotColumnHeaders =
COALESCE(
#PivotColumnHeaders + ',[' + cast(Codigo as varchar) + ']',
'[' + cast(Codigo as varchar)+ ']'
)
FROM RubroCalificaciones
inner join RubrosMetodosEvaluacion on RubroCalificaciones.IdRubro = RubrosMetodosEvaluacion.IdRubro
inner join MetodosEvaluacion on RubrosMetodosEvaluacion.IdMetodoEvaluacion = MetodosEvaluacion.IdMetodoEvaluacion
inner join AsignacionesMetodosEvaluacion on AsignacionesMetodosEvaluacion.IdMetodoEvaluacion = MetodosEvaluacion.IdMetodoEvaluacion
where AsignacionesMetodosEvaluacion.IdGrupo = #IdGrupo--293856
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
select Estudiantes.Matricula, Personas.Nombres, Personas.Apellido1, personas.Apellido2,
RubroCalificaciones.Codigo, CalificacionesDetalle.PuntosAsignados
from Matriculas
inner join Personas on Matriculas.IdPersona = Personas.IdPersona
inner join Estudiantes on Matriculas.IdPersona = Estudiantes.IdPersona
inner join AsignacionesMetodosEvaluacion on Matriculas.IdGrupo = AsignacionesMetodosEvaluacion.IdGrupo
inner join MetodosEvaluacion on AsignacionesMetodosEvaluacion.IdMetodoEvaluacion = MetodosEvaluacion.IdMetodoEvaluacion
inner join RubrosMetodosEvaluacion on MetodosEvaluacion.IdMetodoEvaluacion = RubrosMetodosEvaluacion.IdMetodoEvaluacion
inner join RubroCalificaciones on RubroCalificaciones.IdRubro = RubrosMetodosEvaluacion.IdRubro
left outer join CalificacionesDetalle on CalificacionesDetalle.IdRubro = RubrosMetodosEvaluacion.IdRubro and
CalificacionesDetalle.IdMetodoEvaluacion = RubrosMetodosEvaluacion.IdMetodoEvaluacion
and CalificacionesDetalle.IdMatricula = Matriculas.IdMatricula
where Matriculas.IdGrupo = #IdGrupo--293856
) AS PivotData
PIVOT (
max(PuntosAsignados)
FOR Codigo IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
'
EXECUTE(#PivotTableSQL)
You need to pass your variable into the dynamic SQL. Also, I rewrote the COALESCE , you only need the column once.
CREATE PROC NameThisProcedure
#IdGrupo int
AS
------LISTADO DE calificaciones de ESTUDIANTES
DECLARE #PivotColumnHeaders VARCHAR(MAX)
SELECT #PivotColumnHeaders =
COALESCE(
#PivotColumnHeaders + ',', '') + '[' + cast(Codigo as varchar)+ ']'
FROM RubroCalificaciones
inner join RubrosMetodosEvaluacion on RubroCalificaciones.IdRubro = RubrosMetodosEvaluacion.IdRubro
inner join MetodosEvaluacion on RubrosMetodosEvaluacion.IdMetodoEvaluacion = MetodosEvaluacion.IdMetodoEvaluacion
inner join AsignacionesMetodosEvaluacion on AsignacionesMetodosEvaluacion.IdMetodoEvaluacion = MetodosEvaluacion.IdMetodoEvaluacion
where AsignacionesMetodosEvaluacion.IdGrupo = #IdGrupo--293856
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
select Estudiantes.Matricula, Personas.Nombres, Personas.Apellido1, personas.Apellido2,
RubroCalificaciones.Codigo, CalificacionesDetalle.PuntosAsignados
from Matriculas
inner join Personas on Matriculas.IdPersona = Personas.IdPersona
inner join Estudiantes on Matriculas.IdPersona = Estudiantes.IdPersona
inner join AsignacionesMetodosEvaluacion on Matriculas.IdGrupo = AsignacionesMetodosEvaluacion.IdGrupo
inner join MetodosEvaluacion on AsignacionesMetodosEvaluacion.IdMetodoEvaluacion = MetodosEvaluacion.IdMetodoEvaluacion
inner join RubrosMetodosEvaluacion on MetodosEvaluacion.IdMetodoEvaluacion = RubrosMetodosEvaluacion.IdMetodoEvaluacion
inner join RubroCalificaciones on RubroCalificaciones.IdRubro = RubrosMetodosEvaluacion.IdRubro
left outer join CalificacionesDetalle on CalificacionesDetalle.IdRubro = RubrosMetodosEvaluacion.IdRubro and
CalificacionesDetalle.IdMetodoEvaluacion = RubrosMetodosEvaluacion.IdMetodoEvaluacion
and CalificacionesDetalle.IdMatricula = Matriculas.IdMatricula
where Matriculas.IdGrupo = #IdGrupo--293856
) AS PivotData
PIVOT (
max(PuntosAsignados)
FOR Codigo IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
'
EXECUTE sp_executeSQL #PivotTableSQL, N'#IdGrupo int', #IdGrupo
GO