WITH c AS
(SELECT A.QuestionHdrKey AS QuestionHdrKey1,
A.DivisionKey AS DivisionKey1,
COUNT(1) AS QCount
FROM Mobile.QuestionLocationMap A WITH (NOLOCK)
INNER JOIN Mobile.Question b WITH (NOLOCK) ON A.QuestionKey = b.PKey
WHERE A.QuestionHdrKey = 200305685377000000
GROUP BY A.QuestionHdrKey,
A.DivisionKey),
d AS
(SELECT a.QuestionHdrKey,
a.QuestionKey,
a.DivisionKey,
a.InvDate,
a.HdrKey,
ROW_NUMBER() OVER (PARTITION BY a.DivisionKey,
a.invdate,
a.HdrKey
ORDER BY a.QuestionKey) AS RowId
FROM mobile.StatusReport a WITH (NOLOCK)
INNER JOIN mobile.Question b WITH (NOLOCK) ON a.QuestionKey = b.PKey
AND b.QuestionType = 'rate'
AND InputType = 'numeric'
WHERE a.QuestionHdrKey = '200305685377000000'
GROUP BY a.QuestionHdrKey,
a.DivisionKey,
a.HdrKey,
a.InvDate,
a.QuestionKey)
SELECT a.DivisionKey,
a.InvDate AS ModifiedDate,
a.QuestionHdrKey,
a.HdrKey,
COUNT(DISTINCT a.QuestionKey) AS QuestionKey,
SUM(CAST(a.Value AS int)) AS value,
SUM(b.Rate) AS RATE
--case when a.invdate between '2020-05-09' and '2022-03-31' then case when then case when cast(Value as int)*5>5 then 5 else cast(Value as int)*5 end else cast(Value as int) end as value,c.QCount
FROM mobile.StatusReport a WITH (NOLOCK)
INNER JOIN mobile.Question b WITH (NOLOCK) ON a.QuestionKey = b.PKey
AND b.QuestionType = 'rate'
AND InputType = 'numeric'
INNER JOIN c WITH (NOLOCK) ON a.DivisionKey = c.DivisionKey1
INNER JOIN d WITH (NOLOCK) ON a.HdrKey = d.HdrKey
AND a.QuestionKey = d.QuestionKey
WHERE a.QuestionHdrKey = '200305685377000000'
--and a.HdrKey='210305757994230000'
AND d.RowId <= c.QCount
GROUP BY a.DivisionKey,
a.InvDate,
a.QuestionHdrKey,
a.HdrKey,
c.QCount;
I have this table queried in PowerBI which generates the below table:
The SQL is validated successfully in Information Design Tool but when trying to view its values, it shows an error in the code. How do I work around this?
Alright, after figuring out that "with as" doesn't work outside of the select function in the IDS, I've ditched the aliases and used sub-queries.
select HdrKey,a.DivisionKey,InvDate,RowId ,count(b.QuestionKey) as QCount,qCOUNT_,[value],POINT
from
(select distinct a.HdrKey,a.DivisionKey, a.InvDate, ROW_NUMBER() OVER(PARTITION BY QuestionHdrKey, DivisionKey, a.InvDate ORDER BY a.InvDate) AS RowId,
sum(cast([value] as int)) AS [value], COUNT(DISTINCT A.QuestionKey) AS qCOUNT_, SUM(B.Rate) AS POINT
from NominInventory.mobile.StatusReport a with(nolock)
inner join NominInventory.mobile.Question b with(nolock) on a.QuestionKey=b.PKey and B.QuestionType = 'rate' and InputType='numeric'
where a.QuestionHdrKey='200305685377000000'
GROUP BY a.HdrKey,a.DivisionKey, a.InvDate,QuestionHdrKey
) a
inner join NominInventory.Mobile.QuestionLocationMap b with(nolock) on a.DivisionKey=b.DivisionKey and b.QuestionHdrKey = '200305685377000000'
group by HdrKey,a.DivisionKey,InvDate,RowId,qCOUNT_,[value],POINT
having a.RowId<=count(b.QuestionKey)
So I have the following CTE:
with dupeinv AS (
select * from (
select
tci.t_idoc,
tci.t_idat,
ROW_NUMBER() OVER (partition by tci.t_idoc ORDER BY tci.t_idoc, tci.t_idat DESC) as rn
from [ln106].[dbo].tcisli305100 tci
) as t
where t.rn = 1
)
There are duplicates in the above table ([ln106].[dbo].tcisli305100) , hence the CTE to get single values. I want to format just these values in the below query (prefixed with ---)
select 'JCI' as BU,
RTRIM(LTRIM(cl.t_orno)) AS SALES_ORDER_NUMBER
, cl.t_pono AS SALES_ORDER_LINE_NUMBER
, CONCAT(cl.t_shpm, cl.t_pono, cl.t_idoc) AS SHIPPING_RECORD_ID
,CASE WHEN cl.t_dqua = 0 or cl.t_dqua is null THEN cl.t_amti ELSE
cl.t_amti / cl.t_dqua END AS AR_INVOICE_LINE_ITEM_PRICE_LOCAL
, cl.t_line AS AR_INVOICE_LINE_NUMBER
, cl.t_dqua AS AR_INVOICE_LINE_ITEM_QUANTITY
--- , concat(dupeinv.t_idoc,'|',format(dupeinv.t_idat,'MMddyyyy') ---
,ci.t_ccur AS AR_INVOICE_CURRENCY
, ci.t_idat AS AR_INVOICE_DATE
FROM [ln106].[dbo].tcisli310100 cl
LEFT JOIN [ln106].[dbo].tcisli305100 ci ON cl.t_idoc = ci.t_idoc
LEFT JOIN t di on cl.t_doc = di_t_doc
LEFT JOIN (SELECT t_orno,t_pono FROM [ln106].[dbo].ttdsls401100 WHERE t_oltp <> 1 group by t_orno,t_pono) as l --Jed 10162020 Changed the join to prevent duplicate records
ON l.t_orno=cl.t_orno COLLATE SQL_Latin1_General_CP1_CI_AS AND l.t_pono=cl.t_pono
LEFT JOIN dupeinv tci on cl.r_idoc = ci.t_doc
WHERE ci.t_idat > '2017'
Query doesn't like me referencing it in the main query. Can anyone help, or suggest a better idea?
Your final query should look something like this:
WITH dupeinv AS
(SELECT *
FROM
(SELECT tci.t_idoc,
tci.t_idat,
ROW_NUMBER() OVER (PARTITION BY tci.t_idoc
ORDER BY tci.t_idoc,
tci.t_idat DESC) AS rn
FROM [ln106].[dbo].tcisli305100 tci) AS t
WHERE t.rn = 1 )
SELECT 'JCI' AS BU,
RTRIM(LTRIM(cl.t_orno)) AS SALES_ORDER_NUMBER ,
cl.t_pono AS SALES_ORDER_LINE_NUMBER ,
CONCAT(cl.t_shpm, cl.t_pono, cl.t_idoc) AS SHIPPING_RECORD_ID ,
CASE
WHEN cl.t_dqua = 0
OR cl.t_dqua IS NULL THEN cl.t_amti
ELSE cl.t_amti / cl.t_dqua
END AS AR_INVOICE_LINE_ITEM_PRICE_LOCAL ,
cl.t_line AS AR_INVOICE_LINE_NUMBER ,
cl.t_dqua AS AR_INVOICE_LINE_ITEM_QUANTITY ,
concat(dupeinv.t_idoc,
'|',
format(dupeinv.t_idat, 'MMddyyyy')) ,
ci.t_ccur AS AR_INVOICE_CURRENCY ,
ci.t_idat AS AR_INVOICE_DATE
FROM [ln106].[dbo].tcisli310100 cl
LEFT JOIN [ln106].[dbo].tcisli305100 ci ON cl.t_idoc = ci.t_idoc
LEFT JOIN t di ON cl.t_doc = di_t_doc
LEFT JOIN
(SELECT t_orno,
t_pono
FROM [ln106].[dbo].ttdsls401100
WHERE t_oltp <> 1
GROUP BY t_orno,
t_pono) AS l --Jed 10162020 Changed the join to prevent duplicate records
ON l.t_orno=cl.t_orno COLLATE SQL_Latin1_General_CP1_CI_AS
AND l.t_pono=cl.t_pono
LEFT JOIN dupeinv tci ON cl.r_idoc = ci.t_doc
WHERE ci.t_idat > '2017'
SELECT FutureDatedEmployeeRecordsKey INTO #FutureDatedExclude
FROM dbo.vwRptDimEmployee_FutureDated FD1
WHERE EXISTS (SELECT 1 FROM dbo.vwRptDimEmployeeAll EE1 WITH (NOLOCK)
WHERE FD1.EmployeeID = EE1.EmployeeID AND FD1.EmployeeRecord = EE1.EmployeeRecord
AND FD1.JobEffectiveDate = EE1.JobEffectiveDT AND FD1.JobEffectiveDateSequence = EE1.JobEffectiveDateSequence
AND FD1.ActionCode = EE1.ActionCode AND FD1.ActionReasonCode = EE1.ActionReasonCode)
declare #JobStartDate date = '07/01/2014', #JobEndDate date = '06/30/2015'
SELECT DISTINCT
E.LastName,
E.SecondLastName,
E.FirstName,
E.MiddleName,
E.PreferredName,
E.PreferredFirstName,
E.NameAC,
E.LastNameAC,
E.FirstNameAC,
E.MiddleNameAC,
E.GUI,
E.EmployeeID,
E.LPN,
E.GPN,
E.EmployeeRecord,
E.JobEffectiveDT JobEffectiveDate,
E.JobEffectiveDateSequence,
E.ActionCode,
E.Action,
E.ActionDate,
E.ActionReasonCode,
AR.Description ActionReason,
E.EmployeeStatusCode,
E.EmployeeStatusDesc,
CASE WHEN YEAR(E.LeaveEffectiveDT) > 2100 THEN NULL ELSE E.LeaveEffectiveDT END LeaveEffectiveDate,
CASE WHEN YEAR(E.ExpectedReturnDate) > 2100 THEN NULL ELSE E.ExpectedReturnDate END ExpectedReturnDate,
E.FullPartTime,
E.ShiftCode FWACode,
E.Shift FWAName,
E.TeleWork,
E.StandardHoursFrequency,
E.StandardHours,
E.FTE,
E.PaidFTE,
E.OvertimeEligibility,
E.EmployeeClassCode,
E.EmployeeClass,
E.RegularVersusTemporary RegularTemporary,
E.EmployeeType,
E.PersonnelStatusDesc,
E.PersonOrganizationRelationshipCode,
P.PersonOfInterest,
P.PersonOfInterestDesc,
E.PaygroupCode,
E.EmployeeCategoryCode,
E.EmployeeSubcategoryCode,
P.EmploymentCategory,
E.NonEmployeeNonWorkTypeCD NonEmployeeNonWorkTypeCode,
P.NonEmployeeNonWorkTypeDesc,
A.GlobalAssignmentProgramCD GlobalAssignmentProgramCode,
A.GlobalAssignmentProgramDesc,
CASE WHEN YEAR(E.GlobalAssignmentStartDT) > 2100 THEN NULL ELSE E.GlobalAssignmentStartDT END GlobalAssignmentStartDate,
CASE WHEN YEAR(E.GlobalAssignmentEndDT) > 2100 THEN NULL ELSE E.GlobalAssignmentEndDT END GlobalAssignmentEndDate,
E.InPatExPatStatus,
E.HomeCountry,
E.HomeHostCountry HostCountry,
CASE WHEN YEAR(E.EYStartDate) > 2100 THEN NULL ELSE E.EYStartDate END EYStartDate,
CASE WHEN YEAR(E.LastRehireDate) > 2100 THEN NULL ELSE E.LastRehireDate END LastRehireDate,
CASE WHEN YEAR(E.SeniorityDate) > 2100 THEN NULL ELSE E.SeniorityDate END SeniorityDate,
CASE WHEN YEAR(E.EmployeeEffectiveDate) > 2100 THEN NULL ELSE E.EmployeeEffectiveDate END CurrentEmploymentDate,
CASE WHEN YEAR(E.PartnerAdmissionDate) > 2100 THEN NULL ELSE E.PartnerAdmissionDate END PartnerAdmissionDate,
R.RankCDName RankCodeName,
E.Rank,
R.RankDesc,
E.BusinessTitle,--NEW
R.RankGroup1,--NEW
E.GFISRank,
E.ExperienceLevel,
E.GlobalGrade,
E.JobCode,--NEW
E.JobCDDesc JobCodeDesc,--NEW
E.DepartmentCode,
E.DepartmentName,
E.CompanyCode,
C.Description Company,
C.DescrAc CompanyAC,
E.ManagerialCountryCD ManagerialCountry,
O.CodeBlock,
O.BUCD BU,
O.OUCD OU,
O.MUCD MU,
O.SMUCD SMU,
O.BUName,
O.OUName,
O.MUName,
O.SMUName,
O.UserDefSLHierarchy1 ServiceLine,
O.UserDefSLHierarchy2 SubSL1,
O.UserDefSLHierarchy3 SubSL2,
O.AlternateServiceLine,
O.UserDefAreaHierarchy1 BULevel1,
O.UserDefAreaHierarchy2 BULevel2,
O.UserDefAreaHierarchy3 BULevel3,
L.Location LocationCode,
L.City LocationCity,
L.State LocationStateProv,
L.Country LocationCountry,
L.UserDefinedHRGeo1 GeoLevel1,
L.UserDefinedHRGeo2 GeoLevel2,
L.UserDefinedHRGeo3 GeoLevel3,
L.UserDefinedHRGeo4 GeoLevel4,
L.UserDefinedHRGeo5 GeoLevel5,
E.CounselorGUI,--NEW
E.CounselorName,--NEW
E.BillRate,
E.Source,
--**** confidential fields ****
E.GenderCode,
E.TermCD TermCode,
E.TerminationReasonCode,
E.CompensationCurrency,
E.CompensationRate,
E.CompensationFrequency,
E.MonthlyCompensationRate,
E.AnnualCompensationRate,
CASE WHEN YEAR(P.SalaryEffectiveDT) > 2100 THEN NULL ELSE P.SalaryEffectiveDT END SalaryEffectiveDate,
E.SalaryAdminPlanCode,
E.SalaryAdminPlan,
E.SalaryGrade,
CASE WHEN YEAR(E.SalaryGradeEntryDate) > 2100 THEN NULL ELSE E.SalaryGradeEntryDate END SalaryGradeEntryDate,
NULL JobKEY,
NULL RowOrder
FROM dbo.vwRptFactEmployee F WITH (NOLOCK)
INNER JOIN dbo.vwRptDimEmployee E WITH (NOLOCK) ON (F.DimEmployeeKey = E.DimEmployeeKey)
INNER JOIN dbo.vwRptDimRank R WITH (NOLOCK) ON (F.DimRankKey = R.DimRankKey)
INNER JOIN dbo.vwRptDimOrganization O WITH (NOLOCK) ON (F.DimOrganizationKey = O.DimOrganizationKey)
INNER JOIN dbo.vwRptDimLocation L WITH (NOLOCK) ON (F.DimLocationKey = L.DimLocationKey)
INNER JOIN dbo.vwRptDimAssignment A WITH (NOLOCK) ON (F.DimAssignmentKey = A.DimAssignmentKey)
--INNER JOIN dbo.vwRptDimDate D WITH (NOLOCK) ON (F.TransEffectiveDateKey = D.DimDateKey)
INNER JOIN dbo.vwRptDimEmployeeV2 P WITH (NOLOCK) ON (F.DimEmployeeKey = P.DimEmployeeKey)
LEFT OUTER JOIN (SELECT ActionCode, ActionReasonCode, Description, row_number() over (partition by ActionCode, ActionReasonCode order by EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfActionReason WITH (NOLOCK)) AR
ON (AR.ActionCode = E.ActionCode AND AR.ActionReasonCode = E.ActionReasonCode AND AR.RowOrder = 1)
LEFT OUTER JOIN (SELECT DISTINCT C1.*, ROW_NUMBER() OVER (PARTITION BY CompanyCode ORDER BY EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfCompany C1 WITH (NOLOCK)) C
ON (C.CompanyCode = E.CompanyCode AND C.RowOrder = 1)
WHERE (E.JobEffectiveDT BETWEEN #JobStartDate AND #JobEndDate)
-- AND (E.ActionCode in ('ADD','DTA','HIR','POI','REH','PER','TER'))
--AND (O.BUCD+O.OUCD+O.MUCD+O.SMUCD LIKE '%'+#CodeBlock+'%' OR #CodeBlock IS NULL)
--AND (E.GPN = #GPN OR #GPN IS NULL)
--AND (E.GUI = #GUI OR #GUI IS NULL)
--AND (L.UserDefinedHRGeo1 in (#GeoArea) )
AND (L.UserDefinedHRGeo2 in ('UK and Ireland'))
--AND (L.UserDefinedHRGeo3 in (#Country) )
--AND (O.UserDefAreaHierarchy1 in (#Area) )
--AND (O.UserDefAreaHierarchy2 in (#Region) )
--AND (O.UserDefSLHierarchy1 in (#ServiceLine) )
--AND (O.UserDefSLHierarchy2 in (#SubServiceLine) )
--AND (R.RankCD in (#RankCode) )
UNION
SELECT DISTINCT * FROM (
SELECT DISTINCT
ISNULL(E.LastName,N.LastName) LastName,
ISNULL(E.SecondLastName,N.SecondLastName) SecondLastName,
ISNULL(E.FirstName,N.FirstName) FirstName,
ISNULL(E.MiddleName,N.MiddleName) MiddleName,
E.PreferredName,
ISNULL(E.PreferredFirstName,N.PreferredFirstName) PreferredFirstName,
ISNULL(E.NameAC,N.NameAlternateCharacter) NameAC,
E.LastNameAC,
E.FirstNameAC,
E.MiddleNameAC,
E.GUI,
FD.EmployeeID,
FD.LPN,
FD.GPN,
FD.EmployeeRecord,
FD.JobEffectiveDate,
FD.JobEffectiveDateSequence,
FD.ActionCode,
FD.Action,
FD.ActionDate,
FD.ActionReasonCode,
FD.ActionReason,
FD.EmployeeStatusCode,
FD.EmployeeStatus,
NULL LeaveEffectiveDate,
CASE WHEN YEAR(FD.ExpectedReturnDate) > 2100 THEN NULL ELSE FD.ExpectedReturnDate END ExpectedReturnDate,
FD.FullPartTime,
FD.ShiftCode FWACode,
FD.Shift FWAName,
NULL Telework,
FD.StandardHoursFrequency,
NULL StandardHours,
FD.FTE,
FD.PaidFTE,
NULL OvertimeEligibility,
FD.EmployeeClassCode,
FD.EmployeeClass,
FD.RegularVersusTemporary RegularTemporary,
FD.EmployeeType,
NULL PersonnelStatusDesc,
FD.PersonOrganizationRelationshipCode,
NULL PersonOfInterest,
NULL PersonOfInterestDesc,
FD.PaygroupCode,
FD.EmployeeCategoryCode,
FD.EmployeeSubcategoryCode,
NULL EmploymentCategory,
NULL NonEmployeeNonWorkTypeCode,
NULL NonEmployeeNonWorkTypeDesc,
NULL GlobalAssignmentProgramCode,
NULL GlobalAssignmentProgramDesc,
NULL GlobalAssignmentStartDate,
NULL GlobalAssignmentEndDate,
NULL InPatExPatStatus,
NULL HomeCountry,
NULL HostCountry,
NULL EYStartDate,
NULL LastRehireDate,
NULL SeniorityDate,
NULL CurrentEmploymentDate,
NULL PartnerAdmissionDate,
R.RankCDName RankCodeName,
FD.Rank,
R.RankDesc,
FD.BusinessTitle,--NEW
R.RankGroup1,--NEW
FD.GFISRank,
NULL ExperienceLevel,
NULL GlobalGrade,
FD.JobCode,--NEW
NULL JobCodeDesc,--NEW
FD.DepartmentCode,
NULL DepartmentName,
FD.CompanyCode,
C.Description Company,
C.DescrAc CompanyAC,
NULL ManagerialCountry,
O.CodeBlock,
O.BUCD BU,
O.OUCD OU,
O.MUCD MU,
O.SMUCD SMU,
O.BUName,
O.OUName,
O.MUName,
O.SMUName,
O.UserDefSLHierarchy1 ServiceLine,
O.UserDefSLHierarchy2 SubSL1,
O.UserDefSLHierarchy3 SubSL2,
O.AlternateServiceLine,
O.UserDefAreaHierarchy1 BULevel1,
O.UserDefAreaHierarchy2 BULevel2,
O.UserDefAreaHierarchy3 BULevel3,
L.Location LocationCode,
L.City LocationCity,
L.State LocationStateProv,
L.Country LocationCountry,
L.UserDefinedHRGeo1 GeoLevel1,
L.UserDefinedHRGeo2 GeoLevel2,
L.UserDefinedHRGeo3 GeoLevel3,
L.UserDefinedHRGeo4 GeoLevel4,
L.UserDefinedHRGeo5 GeoLevel5,
NULL CounselorGUI,--NEW
NULL CounselorName,--NEW
NULL BillRate,
FD.Source,
--**** confidential fields ****
NULL GenderCode,
NULL TermCode,
FD.TerminationReasonCode,
FD.CompensationCurrency,
FD.CompensationRate,
FD.CompensationFrequency,
FD.MonthlyCompensationRate,
FD.AnnualCompensationRate,
NULL SalaryEffectiveDate,
FD.SalaryAdminPlanCode,
FD.SalaryAdminPlan,
FD.SalaryGrade,
CASE WHEN YEAR(FD.SalaryGradeEntryDate) > 2100 THEN NULL ELSE FD.SalaryGradeEntryDate END SalaryGradeEntryDate,
FD.Job_KEY,
row_number() over (partition by FD.EmployeeID, FD.EmployeeRecord, FD.JobEffectiveDate,
FD.JobEffectiveDateSequence, FD.ActionCode, FD.ActionReasonCode order by FD.Job_KEY DESC) as RowOrder
FROM dbo.vwRptDimEmployee_FutureDated FD
INNER JOIN dbo.vwRptDimOrganization O WITH (NOLOCK) ON (FD.DimOrganizationKey = O.DimOrganizationKey)
INNER JOIN dbo.vwRptDimLocation L WITH (NOLOCK) ON (FD.DimLocationKey = L.DimLocationKey)
LEFT OUTER JOIN dbo.vwRptDimRank R WITH (NOLOCK) ON (FD.Rank = R.RankCD)
LEFT OUTER JOIN dbo.vwRptDimEmployeeAll E WITH (NOLOCK) ON (FD.GPN = E.GPN AND FD.GPN <> '' AND E.RowIsCurrent = 'Y')
LEFT OUTER JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY EmployeeID, NameType ORDER BY EffectiveDate DESC) AS RowOrder
FROM PISupport.vwRptPersonACNames WITH (NOLOCK)
) N ON (N.EmployeeID = FD.EmployeeID AND N.NameType = 'PRI' AND N.CountryNameFormat = FD.SetIDLaborAgreement AND N.RowOrder = 1)
LEFT OUTER JOIN (SELECT DISTINCT C1.*, ROW_NUMBER() OVER (PARTITION BY CompanyCode ORDER BY EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfCompany C1 WITH (NOLOCK)) C
ON (C.CompanyCode = FD.CompanyCode AND C.RowOrder = 1)
WHERE
FD.JobEffectiveDate BETWEEN #JobStartDate AND #JobEndDate
AND FD.EDWIsCurrentRecord = 1
AND FD.EmployeeID IS NOT NULL
--AND (E.ActionCode in ('ADD','DTA','HIR','POI','REH','PER','TER'))
--AND (O.BUCD+O.OUCD+O.MUCD+O.SMUCD LIKE '%'+#CodeBlock+'%' OR #CodeBlock IS NULL)
--AND (FD.GPN = #GPN OR #GPN IS NULL)
--AND (L.UserDefinedHRGeo1 in (#GeoArea) )
AND (L.UserDefinedHRGeo2 in ('UK and Ireland'))
--AND (L.UserDefinedHRGeo3 in (#Country) )
--AND (O.UserDefAreaHierarchy1 in (#Area) )
--AND (O.UserDefAreaHierarchy2 in (#Region) )
--AND (O.UserDefSLHierarchy1 in (#ServiceLine) )
--AND (O.UserDefSLHierarchy2 in (#SubServiceLine) )
--AND (FD.Rank in (#RankCode) )
AND FD.FutureDatedEmployeeRecordsKey NOT IN (SELECT FutureDatedEmployeeRecordsKey FROM #FutureDatedExclude)
) X
WHERE RowOrder = 1
DROP TABLE #FutureDatedExclude
You most likely ran this code before you added the DROP TABLE at the bottom of your code. Therefore, the table is created and yet to be dropped. Instead of dropping it at the end, or in addition to dropping it if you want, place this at the very top of your script:
IF OBJECT_ID('tempdb..#FutureDatedExclude') IS NOT NULL DROP TABLE #FutureDatedExclude
I am using the following SQL code to JOIN a few tables, but need to show unique values for the s.incidentid based on the latest s.createdate.
I know I need to use a Sub query with Maxdate, but I am not sure on the correct syntax.
This is my first query with multiple joins and I am struggling to get my head round it.
Here is my code:
SELECT
s.incidentid,
u.internalid as AssignedTo,
u.fullname as AssignedTo_FullName,
s.createby as AssignedBy,
u2.fullname as AssignedBy_FullName,
s.createdate as AssignedTime,
i.[description],
i.fix,
st.[description] as [Status],
(SELECT (CASE WHEN u.internalid = s.createby THEN 'Yes' ELSE 'No' END) as SelfAssigned),
d.d1,
d.d2,
d.d3,
d.d4,
d.d5
FROM dbo.IncidentServiceLevelAgreement s
JOIN dbo.UserAll u on u.userid = s.userid
JOIN dbo.UserAll u2 on u2.internalid = s.createby
JOIN dbo.IncidentAll i on s.incidentid = i.incidentid
JOIN dbo.[Status] st on i.statusid = st.statusid
JOIN dbo.flatdiagnosis d on i.actualdiagnosisid = d.diagnosisid
WHERE (s.groupId = '4954' and s.incidentServiceLevelAgreementTypeID = '9')
ORDER BY AssignedTime DESC
Any help greatly appreciated.
The easiest is to use a CTE and the ROW_NUMBER function:
WITH CTE AS
(
SELECT RN = ROW_NUMBER() OVER ( PARTITION BY incidentid
ORDER BY createdate DESC ),
s.Incidentid,
u.Internalid AS AssignedTo,
u.Fullname AS AssignedTo_FullName,
s.Createby AS AssignedBy,
u2.Fullname AS AssignedBy_FullName,
s.Createdate AS AssignedTime,
i.[Description],
i.Fix,
st.[Description] AS [Status],
SelfAssigned = CASE WHEN u.Internalid = s.Createby
THEN 'Yes' ELSE 'No' END,
d.D1,
d.D2,
d.D3,
d.D4,
d.D5
FROM dbo.Incidentservicelevelagreement s
JOIN dbo.Userall u
ON u.Userid = s.Userid
JOIN dbo.Userall u2
ON u2.Internalid = s.Createby
JOIN dbo.Incidentall i
ON s.Incidentid = i.Incidentid
JOIN dbo.[Status] st
ON i.Statusid = st.Statusid
JOIN dbo.Flatdiagnosis d
ON i.Actualdiagnosisid = d.Diagnosisid
WHERE ( s.Groupid = '4954'
AND s.Incidentservicelevelagreementtypeid = '9' )
)
SELECT * FROM CTE WHERE RN = 1
ORDER BY AssignedTime DESC
(instead of SELECT * list all columns explicitly, I didn't feel like it)
A logistic regression is a composed of a uniquely identifying number, followed by multiple binary variables (always 1 or 0) based on whether or not a person meets certain criteria. Below I have a query that lists several of these binary conditions. With only four such criteria the query takes a little longer to run than what I would think. Is there a more efficient approach than below? Note. tblicd is a large table lookup table with text representations of 15k+ rows. The query makes no real sense, just a proof of concept. I have the proper indexes on my composite keys.
select patient.patientid
,case when exists
(
select c.patientid from tblclaims as c
inner join patient as p on p.patientid=c.patientid
and c.admissiondate = p.admissiondate
and c.dischargedate = p.dischargedate
where patient.patientid = p.patientid
group by c.patientid
having count(*) > 1000
)
then '1' else '0'
end as moreThan1000
,case when exists
(
select c.patientid from tblclaims as c
inner join patient as p on p.patientid=c.patientid
and c.admissiondate = p.admissiondate
and c.dischargedate = p.dischargedate
where patient.patientid = p.patientid
group by c.patientid
having count(*) > 1500
)
then '1' else '0'
end as moreThan1500
,case when exists
(
select distinct picd.patientid from patienticd as picd
inner join patient as p on p.patientid= picd.patientid
and picd.admissiondate = p.admissiondate
and picd.dischargedate = p.dischargedate
inner join tblicd as t on t.icd_id = picd.icd_id
where t.descrip like '%diabetes%' and patient.patientid = picd.patientid
)
then '1' else '0'
end as diabetes
,case when exists
(
select r.patientid, count(*) from patient as r
where r.patientid = patient.patientid
group by r.patientid
having count(*) >1
)
then '1' else '0'
end
from patient
order by moreThan1000 desc
I would start by using subqueries in the from clause:
select q.patientid, moreThan1000, moreThan1500,
(case when d.patientid is not null then 1 else 0 end),
(case when pc.patientid is not null then 1 else 0 end)
from patient p left outer join
(select c.patientid,
(case when count(*) > 1000 then 1 else 0 end) as moreThan1000,
(case when count(*) > 1500 then 1 else 0 end) as moreThan1500
from tblclaims as c inner join
patient as p
on p.patientid=c.patientid and
c.admissiondate = p.admissiondate and
c.dischargedate = p.dischargedate
group by c.patientid
) q
on p.patientid = q.patientid left outer join
(select distinct picd.patientid
from patienticd as picd inner join
patient as p
on p.patientid= picd.patientid and
picd.admissiondate = p.admissiondate and
picd.dischargedate = p.dischargedate inner join
tblicd as t
on t.icd_id = picd.icd_id
where t.descrip like '%diabetes%'
) d
on p.patientid = d.patientid left outer join
(select r.patientid, count(*) as cnt
from patient as r
group by r.patientid
having count(*) >1
) pc
on p.patientid = pc.patientid
order by 2 desc
You can then probably simplify these subqueries more by combining them (for instance "p" and "pc" on the outer query can be combined into one). However, without the correlated subqueries, SQL Server should find it easier to optimize the queries.
Example of left joins as requested...
SELECT
patientid,
ISNULL(CondA.ConditionA,0) as IsConditionA,
ISNULL(CondB.ConditionB,0) as IsConditionB,
....
FROM
patient
LEFT JOIN
(SELECT DISTINCT patientid, 1 as ConditionA from ... where ... ) CondA
ON patient.patientid = CondA.patientID
LEFT JOIN
(SELECT DISTINCT patientid, 1 as ConditionB from ... where ... ) CondB
ON patient.patientid = CondB.patientID
If your Condition queries only return a maximum one row, you can simplify them down to
(SELECT patientid, 1 as ConditionA from ... where ... ) CondA