I have big data and multiple LEFT JOINs for same table as below query
I have view AB_AccCard which contains columns [YID] and [YParentID]
what I want is to look for [YID] in [AB_ProcessDetail] and get YParentID from [AB_AccCard] then save it as [YParent]
then get [YParentID] for new [YParent] and save it as [YParent2]
then get [YParentID] for new [YParent2] and save it as [YParent3]
..... want this for 5 level
SELECT
YPartner = ISNULL(AP.AccName, AC.AccName),
YPartner2 = ISNULL(AP2.AccName, ISNULL(AP.AccName, AC.AccName)),
YPartner3 = ISNULL(AP3.AccName, ISNULL(AP2.AccName, ISNULL(AP.AccName, AC.AccName))),
YPartner4 = ISNULL(AP4.AccName, ISNULL(AP3.AccName, ISNULL(AP2.AccName, ISNULL(AP.AccName, AC.AccName)))),
YPartner5 = ISNULL(AP5.AccName, ISNULL(AP4.AccName, ISNULL(AP3.AccName, ISNULL(AP2.AccName, ISNULL(AP.AccName, AC.AccName)))))
FROM
dbo.[AB_ProcessDetail] A WITH(NOLOCK)
LEFT JOIN
AB_AccCard AC WITH(NOLOCK) ON AC.YID = A.YAccCardId
AND a.DataBaseName = ac.DataBaseName
LEFT JOIN
(SELECT YID, AccName, YParentID, AccType, DataBaseName
FROM dbo.AB_AccCard WITH(NOLOCK)) AP ON AP.YID = ac.YParentID
AND AP.DataBaseName = AC.DataBaseName
LEFT JOIN
(SELECT YID, AccName, YParentID, AccType, DataBaseName
FROM dbo.AB_AccCard WITH(NOLOCK)) AP2 ON AP2.YID = AP.YParentID
AND AP2.DataBaseName = AC.DataBaseName
LEFT JOIN
(SELECT YID, AccName, YParentID, AccType, DataBaseName
FROM dbo.AB_AccCard WITH(NOLOCK)) AP3 ON AP3.YID = AP2.YParentID
AND AP3.DataBaseName = AC.DataBaseName
LEFT JOIN
(SELECT YID, AccName, YParentID, AccType, DataBaseName
FROM dbo.AB_AccCard WITH(NOLOCK)) AP4 ON AP4.YID = AP3.YParentID
AND AP4.DataBaseName = AC.DataBaseName
LEFT JOIN
(SELECT YID, AccName, YParentID, AccType, DataBaseName
FROM dbo.AB_AccCard WITH(NOLOCK)) AP5 ON AP5.YID = AP4.YParentID
AND AP5.DataBaseName = AC.DataBaseName
It takes a long time to execute.
How can I make it go faster?
I have used OUTER APPLY with FUNCTION
CREATE FUNCTION [dbo].[fnAB_GetPartnerID] (#YParentID varchar(25),#DataBaseName varchar(4) )
RETURNS TABLE
AS
RETURN
(
SELECT E.CardType,E.Code,E.AccName,E.YID, E.AccType,E.YParentID,E.DataBaseName
FROM AB_AccCard E WITH(NOLOCK)
WHERE e.YID = #YParentID AND E.DataBaseName =#DataBaseName
)
And the query is
SELECT
YPartner = ISNULL(AP.AccName,AC.AccName),
YPartner2 = ISNULL(AP2.AccName,ISNULL(AP.AccName,AC.AccName)),
YPartner3 = ISNULL(AP3.AccName,ISNULL(AP2.AccName,ISNULL(AP.AccName,AC.AccName))),
YPartner4 = ISNULL(AP4.AccName,ISNULL(AP3.AccName,ISNULL(AP2.AccName,ISNULL(AP.AccName,AC.AccName)))),
YPartner5 = ISNULL(AP5.AccName,ISNULL(AP4.AccName,ISNULL(AP3.AccName,ISNULL(AP2.AccName,ISNULL(AP.AccName,AC.AccName)))))
FROM [AB_ProcessDetail] A WITH(NOLOCK)
OUTER APPLY fnAB_GetPartnerID (A.YAccCardId , A.DataBaseName ) AC
OUTER APPLY fnAB_GetPartnerID (ac.YParentID ,ac.DataBaseName ) AP
OUTER APPLY fnAB_GetPartnerID (AP.YParentID ,AP.DataBaseName ) AP2
OUTER APPLY fnAB_GetPartnerID (AP2.YParentID ,AP2.DataBaseName ) AP3
OUTER APPLY fnAB_GetPartnerID (AP3.YParentID ,AP3.DataBaseName ) AP4
OUTER APPLY fnAB_GetPartnerID (AP4.YParentID ,AP4.DataBaseName ) AP5
But I still wonder if there is a better way
Related
i have query below
SELECT #RoleUser = MR.Code FROM MasterRole MR INNER JOIN MasterUsersRole MUR ON MR.Id = MUR.RoleId
INNER JOIN MasterUsers MU ON Mu.UserCode = MUR.UserCode
WHERE MU.UserCode = #UserLoginID
select 1 Num
, MyHistory.ID
, MyHistory.RequestNumber
, MyHistory.FlowID
, MyHistory.FlowProcessStatusID
from
(
select *
from Requests R
inner join
(
--DECLARE #UserLoginID nvarchar(200) = 'dum.testing.3'
select distinct
RequestID
from dbo.RequestTrackingHistory RTH
where IIF(#UserLoginID = 'admin', #UserLoginID, RTH.CreatedBy) = #UserLoginID
OR ( CreatedBy IN
SELECT Mu.UserCode from MasterUsers MU
INNER JOIN MasterUsersRole MUR ON MU.UserCode = MUR.UserCode
INNER JOIN MasterRole MR ON MUR.RoleId = MR.Id
WHERE MR.Code = #RoleUser
)
)
) RT on R.ID = RT.RequestID
) as MyHistory
inner join MasterFlow F on MyHistory.FlowID = F.ID
inner join
(
select FP.ID
, FP.Name
, FP.AssignType
, FP.AssignTo
, FP.IsStart
, case FP.AssignType
when 'GROUP' then
G.Name
end as 'AssignToName'
from MasterFlowProcess FP
left join dbo.MasterRole G on FP.AssignTo = G.ID and FP.AssignType = 'GROUP'
) FP on MyHistory.FlowProcessID = FP.ID
inner join MasterFlowProcessStatus FPS on MyHistory.FlowProcessStatusID = FPS.ID
left join MasterFlowProcessStatusNext FPSN on FPS.ID = FPSN.ProcessStatusFlowID
left join MasterFlowProcess FPN on FPSN.NextProcessFlowID = FPN.ID
left JOIN MasterRole MR ON MR.Id = FPN.AssignTo
left join MasterUsersRole MUR on MR.Id = MUR.RoleId
left join MasterUsers MURO on MUR.UserCode = MURO.UserCode
inner join MasterUsers UC on MyHistory.CreatedBy = UC.UserCode
left join MasterUsers UU on MyHistory.UpdatedBy = UU.UserCode
LEFT JOIN RequestMT RMT ON MyHistory.ID = RMT.RequestID
LEFT JOIN RequestGT RGT ON MyHistory.ID = RGT.RequestID
left join (SELECT sum(QtyCU) countQty , RequestId from dbo.RequestGTDetail where IsActive = 1 group by RequestId) RGTD on RGTD.RequestId = RGT.RequestId
left join (SELECT sum(QtyPCS) countQty , RequestId from dbo.RequestMTDetail where IsActive = 1 group by RequestId) RMTD on RMTD.RequestId = RMT.RequestId
left join (SELECT COUNT(IIF(returnable = 0, returnable, null)) countReturnable , RequestId from dbo.RequestMTDetail group by RequestId) RMTR on RMTR.RequestId = RMT.RequestId
left JOIN dbo.MasterDistributor md ON md.Code = RGT.CustId or md.Code = RMT.CustId
left JOIN dbo.MasterUsersDistributor MUD ON MUD.UserCode = MURO.UserCode AND md.Code = MUD.DistributorCode
LEFT JOIN dbo.MasterReason MRMT ON RMT.ReasonId = MRMT.Id
LEFT JOIN dbo.MasterReason MRGT ON RGT.ReasonId = MRGT.Id
LEFT JOIN dbo.MasterDistributorGroup MDG ON MDG.Id = MD.GroupId
OUTER APPLY dbo.FnGetHistoryApproveDate(MyHistory.Id) AS x
where REPLACE(FPS.Name, '#Requestor', uc.Name) <> 'DRAFT'
AND MUD.DistributorCode IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = #UserLoginID)
i want to add some logic in where clause
this line
==> AND MUD.DistributorCode IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = #UserLoginID)
it depend on the #RoleUser variable, if #RoleUser IN ('A','B') then where clause above is executed, but if #RoleUser Not IN ('A','B') where clause not executed
i,m trying this where clause
AND IIF(#RoleUser IN ('A','B'), MUD.DistributorCode, #RoleUser) IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = IIF(#RoleUser IN ('A','B'), #UserLoginID, NULL))
it didn't work, only executed if #RoleUser IS ('A','B') other than that it return 0 record
any help or advice is really appreciated
thank you
The cleanest way I'm implemented these kind of crazy rules is a
holderTable
and a countVariable against the holder table.
I'll give a generic examples.
This is a "approach" and "philosophy", not a specific answer....with complex WHERE clauses.
DECLARE #customerCountryCount int
DECLARE #customerCountry TABLE ( CountryName varchar(15) )
if ( "the moon is blue on tuesday" ) /* << whatever rules you have */
BEGIN
INSERT INTO #customerCountry SELECT "Honduras" UNION ALL SELECT "Malaysia"
END
if ( "favorite color = green" ) /* << whatever rules you have */
BEGIN
INSERT INTO #customerCountry SELECT "Greenland" UNION ALL SELECT "Peru"
END
SELECT #customerCountryCount = COUNT(*) FROM #customerCountry
Select * from dbo.Customers c
WHERE
(#customerCountryCount = 0)
OR
( exists (select null from #customerCountry innerVariableTable where UPPER(innerVariableTable.CountryName) = UPPER(c.Country) ))
)
This way, instead of putting all the "twisted logic" in an overly complex WHERE statement..... you have "separation of concerns"...
Your inserts into #customerCountry are separated from your use of #customerCountry.
And you have the #customerCountryCount "trick" to distinguish when nothing was used.
You can add a #customerCountryNotExists table as well, and code it to where not exists.
As a side note, you may want to try using a #temp table (instead of a #variabletable (#customerCountry above)... and performance test these 2 options.
There is no "single answer". You have to "try it out".
And many many variables go into #temp table performance (from a sql-server SETUP, not "how you code a stored procedure". That is way outside the scope of this question.
Here is a SOF link to "safe" #temp table usage.
Temporary table in SQL server causing ' There is already an object named' error
I have 2 queries that I want to optimize but I don't know how. The execution time is not acceptable for me.
I'm working with jira database and did query to show different tasks with some attributes.
The code is:
SET NOCOUNT ON
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка'
,p.[pname] AS 'П'
,users.[display_name] AS 'Исполнитель'
,CAST(ji.[CREATED] AS smalldatetime) AS 'Создан'
,CAST(ji.[RESOLUTIONDATE] AS smalldatetime) AS 'Дата резолюции'
,ji.[issuenum]
INTO #TT
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON (p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] as users ON (users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND itype.pname = 'Incident'
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,system_t.[NAME] AS 'Контур ИС'
,system_t_t.[NAME] AS 'Критичность системы'
INTO #TT1
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t ON (system_t.[ID] = substring(customfv.[STRINGVALUE], PatIndex('%[0-9]%', customfv.[STRINGVALUE]), len(customfv.[STRINGVALUE])))
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR] AS system_attr ON (system_t.[ID] = system_attr.[OBJECT_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR_VAL] AS system_attr_val ON (system_attr.[ID] = system_attr_val.[OBJECT_ATTRIBUTE_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t_t ON (system_attr_val.[REFERENCED_OBJECT_ID] = system_t_t.[ID])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND (customfv.[CUSTOMFIELD] = 21003 OR customfv.[CUSTOMFIELD] = 21005)
AND (system_t.[OBJECT_TYPE_ID] = 136 OR system_t.[OBJECT_TYPE_ID] = 303 OR system_t.[OBJECT_TYPE_ID] = 143)
AND system_attr.[OBJECT_TYPE_ATTRIBUTE_ID] = 461
AND itype.pname = 'Incident'
SELECT ji.[issuenum]
,pr_pr.[pname] AS '(project) Project'
INTO #TT2
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [project] AS pr_pr ON (pr_pr.[ID] = CAST(customfv.[NUMBERVALUE] AS BIGINT))
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND pr_pr.[pname] is not NULL
SELECT CTE.[Ключ], CTE.[Ссылка], CTE.[П], CTE.[Исполнитель], CTE.[Создан], CTE.[Дата резолюции], CTE2.[(project) Project], CTE1.[Контур ИС], CTE1.[Критичность системы], CTE.[issuenum]
FROM #TT CTE
LEFT OUTER JOIN #TT1 CTE1 ON (CTE1.[Ключ] = CTE.[Ключ])
LEFT OUTER JOIN #TT2 CTE2 ON (CTE2.[issuenum] = CTE.[issuenum])
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
There will be some information for the month before last.
summary of query
The next query is:
WITH CTE AS (
SELECT concat(p.pkey,'-',i.issuenum) AS 'Ключ',
cf.cfname,
cv.textvalue,
ROW_NUMBER() OVER (PARTITION BY i.issuenum ORDER BY i.issuenum) AS RowNumber_SLA
FROM customfield cf,
customfieldvalue cv,
jiraissue i,
project p
WHERE i.project = p.id
AND cv.issue = i.id
AND cv.customfield = cf.id
AND cf.customfieldtypekey = 'com.atlassian.servicedesk:sd-sla-field'
and i.issuenum IN ()
and CHARINDEX('"succeeded":false', TEXTVALUE) >0
)
SELECT CTE.Ключ
FROM CTE
WHERE RowNumber_SLA = 1
The goal is to get tasks where SLA has been failed.
So in and i.issuenum IN () my Python script is putting issue numbers that I got through previous query.
The average execution time is 3 minutes.
So, I want optimize this too, maybe join first query.
Sorry for my English. I'm not an English-speaking person.
P. S. Changing CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done' to ci.[NEWSTRING] = 'Done' causing the error The data types ntext and varchar are incompatible in the equal to operator. Workaround - ci.[NEWSTRING] LIKE 'Done' fixing this.
The first query must be rewrite as :
SELECT DISTINCT
concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ',
concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка',
p.[pname] AS 'П',
users.[display_name] AS 'Исполнитель',
CAST(ji.[CREATED] AS SMALLDATETIME) AS 'Создан',
CAST(ji.[RESOLUTIONDATE] AS SMALLDATETIME) AS 'Дата резолюции',
ji.[issuenum]
INTO #TT
FROM [jiraissue] AS ji
INNER JOIN [changegroup] AS cg ON(cg.[issueid] = ji.[id])
INNER JOIN [changeitem] AS ci ON(ci.[groupid] = cg.[id])
AND ci.FIELDTYPE = 'jira'
AND ci.FIELD = 'status'
LEFT OUTER JOIN [app_user] AS au ON(au.[user_key] = cg.[AUTHOR])
INNER JOIN [issuetype] AS itype ON(itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON(p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON(pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] AS users ON(users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(DATETIME, '2021-12-01')
AND cg.[CREATED] <= CONVERT(DATETIME, '2022-01-01')
AND ci.[NEWSTRING] = 'Done'
AND itype.pname = 'Incident';
False outer joins are converted in INNER and I have aslo eliminate the ugly CONVERT to NVARCHAR(max)
Same troubles appears in the second query...
I have a simplified query shown below, that does mulitple joins. I'm trying to add a field to be selected but I am unable to find a good way of joining it without changing the number of records that come up...
SELECT tblApp.AppID
,'Type' = tblRef.Label
,'Status' = tblRef2.Label
FROM (
(
(
tblApp LEFT JOIN tblAppExt ON tblApp.AppID = tblAppExt.AppID
) LEFT JOIN tblRef ON tblApp.AppTypeID = tblReferenceData.ID
) LEFT JOIN tblRef tblRef2 ON tblApp.AppStatusID = tblRef2.ID
)
As is - I'm getting 149 results, if I try to Join it in any way, I get like 10 time fold the number of records. All I'm hoping to do is be able to SELECt another field. I'm hoping to join tblAppExt2 that has AppID just like the other tables in the FROM part of the query, so my goal would basically be to do this:
SELECT tblApp.AppID
,'Type' = tblRef.Label
,'Status' = tblRef2.Label
,'NewField' = tblAppExt2.NewField
First thing to try is DISTINCT:
SELECT DISTINCT
tblApp.AppID
, [Type] = tblRef.Label
, [Status] = tblRef2.Label
, [NewField] = tblAppExt2.NewField
FROM tblApp
LEFT JOIN tblAppExt
ON tblApp.AppID = tblAppExt.AppID
LEFT JOIN tblRef
ON tblApp.AppTypeID = tblReferenceData.ID
LEFT JOIN tblRef tblRef2
ON tblApp.AppStatusID = tblRef2.ID
LEFT JOIN tblAppExt2.NewField
ON something = somethingElse ;
If that doesn't work, it means there are multiple different values for [NewField] and you'll need to tell it how to select the correct one. For example, to take the most recent [NewField] you can use a CTE with the ROW_NUMBER function:
; WITH AllRecords
AS (
SELECT DISTINCT
tblApp.AppID
, [Type] = tblRef.Label
, [Status] = tblRef2.Label
, [NewField] = tblAppExt2.NewField
, MyRank = ROW_NUMBER() OVER(PARTITION BY tblApp.ID ORDER BY tblAppExt2.DateEntered DESC)
FROM tblApp
LEFT JOIN tblAppExt
ON tblApp.AppID = tblAppExt.AppID
LEFT JOIN tblRef
ON tblApp.AppTypeID = tblReferenceData.ID
LEFT JOIN tblRef tblRef2
ON tblApp.AppStatusID = tblRef2.ID
LEFT JOIN tblAppExt2.NewField
ON something = somethingElse
)
SELECT *
FROM AllRecords
WHERE AllRecords.MyRank = 1 ;
You can use outer apply or correlated subquery :
SELECT tblApp.AppID, tblRef.Label as [Type], tblRef2.Label as [Status],
tappext.NewField
FROM tblApp tapp LEFT JOIN
tblAppExt tex
ON tapp.AppID = tex.AppID LEFT JOIN
tblRef tref
ON tapp.AppTypeID = tref.ID LEFT JOIN
tblRef tblRef2
ON tapp.AppStatusID = tblRef2.ID OUTER APPLY
( SELECT TOP (1) tappext.*
FROM tblAppExt2 tappext
WHERE tapp.AppID = AppID
ORDER BY ??
) tappext;
I am trying to sort the record on milestone id coloumn but it is throwing error at order by in subquery giving error as "The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified."
CREATE PROCEDURE [dbo].[spGetALLStudyCodedtls]
(
#StudyCodeId VARCHAR(MAX)
)
AS
BEGIN
SELECT X.[IsActive]
--scd.[StudyCodeId]
,
X.[StudyCode],
X.[ProductName],
X.[TherapyName],
X.[Dosage],
X.[StudyType],
X.[Condition],
X.[CountryName],
X.[CRO],
X.[Design],
X.[DesignTag],
X.[RnD ProjManager],
X.[Project Manager],
X.[IPDFillingTimeline],
X.[Comments],
X.[MileStoneId],
X.[Milestone],
X.[Category],
X.[BaseLineDate],
X.[ActualDate]
FROM (
SELECT sc.IsActive
--scd.[StudyCodeId]
,
scd.[StudyCode],
pm.ProductName,
tm.TherapyName,
dm.Dosage,
stm.StudyType,
com.Condition,
cn.CountryName,
crm.CRO,
dsm.Design,
dtm.DesignTag,
ud.[user_name] AS 'RnD ProjManager',
udd.[user_name] AS 'Project Manager',
scd.[IPDFillingTimeline],
scd.[Remarks] AS 'Comments',
mm.MileStoneId,
mm.MileStoneName AS 'Milestone',
mm.Category AS 'Category',
sc.[BaseLineDate],
sc.[ActualDate]
FROM [PMS].[dbo].[StudyCodeDetails] scd
INNER JOIN [dbo].[StudyCodeToMileStone] sc ON scd.StudyCodeId = sc.StudyCodeId
INNER JOIN [dbo].[MileStoneMaster] mm ON sc.MileStoneId = mm.MileStoneId
INNER JOIN dbo.ProductMaster pm ON scd.ProductId = pm.ProductId
INNER JOIN dbo.TherapyMaster tm ON tm.TherapyId = scd.TherapyId
INNER JOIN dbo.DosageMaster dm ON dm.DosageId = scd.DosageId
INNER JOIN dbo.CountryMaster cn ON cn.CountryId = scd.CountryId
INNER JOIN dbo.[User_Dtls] ud ON ud.Pk_ID = scd.RnDProjManagerId
INNER JOIN dbo.[User_Dtls] udd ON udd.Pk_ID = scd.ProjectManagerId
INNER JOIN dbo.CroMaster crm ON crm.CroId = scd.CRO
INNER JOIN dbo.DesignMaster dsm ON dsm.DesignId = scd.DesignId
INNER JOIN dbo.DesignTagMaster dtm ON dtm.DesignTagId = scd.DesignTagId
INNER JOIN dbo.StudyTypeMaster stm ON stm.StudyTypeId = scd.StudyTypeId
INNER JOIN dbo.ConditionMaster com ON com.ConditionId = scd.Condition
WHERE scd.StudyCodeId IN (
SELECT CAST(Item AS INTEGER)
FROM [dbo].[SplitString](#StudyCodeId, ',')
)
AND mm.[AdditionalPayment] = 0
ORDER BY mm.MileStoneId
) AS X
GROUP BY X.[IsActive]
--scd.[StudyCodeId]
,
X.[StudyCode],
X.[ProductName],
X.[TherapyName],
X.[Dosage],
X.[StudyType],
X.[Condition],
X.[CountryName],
X.[CRO],
X.[Design],
X.[DesignTag],
X.[RnD ProjManager],
X.[Project Manager],
X.[IPDFillingTimeline],
X.[Comments],
X.[MileStoneId],
X.[Milestone],
X.[Category],
X.[BaseLineDate],
X.[ActualDate]
END
Please try this one:
CREATE PROCEDURE [dbo].[spGetALLStudyCodedtls]
(
#StudyCodeId VARCHAR(MAX)
)
AS
BEGIN
SELECT X.[IsActive]
--scd.[StudyCodeId]
,
X.[StudyCode],
X.[ProductName],
X.[TherapyName],
X.[Dosage],
X.[StudyType],
X.[Condition],
X.[CountryName],
X.[CRO],
X.[Design],
X.[DesignTag],
X.[RnD ProjManager],
X.[Project Manager],
X.[IPDFillingTimeline],
X.[Comments],
X.[MileStoneId],
X.[Milestone],
X.[Category],
X.[BaseLineDate],
X.[ActualDate]
FROM (
SELECT t1.IsActive,
t1.[StudyCode],
t2.ProductName,
t2.TherapyName,
t2.Dosage,
t2.StudyType,
t2.Condition,
t2.CountryName,
t2.CRO,
t2.Design,
t2.DesignTag,
t2.[user_name] AS 'RnD ProjManager',
t2.[user_name] AS 'Project Manager',
t1.[IPDFillingTimeline],
scd.[Remarks] AS 'Comments',
t2.MileStoneId,
t2.MileStoneName AS 'Milestone',
t2.Category AS 'Category',
t1.[BaseLineDate],
t1.[ActualDate]
FROM
(
SELECT sc.IsActive,
scd.[StudyCode],
scd.[IPDFillingTimeline],
scd.[Remarks] AS 'Comments',
sc.[BaseLineDate],
sc.[ActualDate],
sc.MileStoneId
FROM [PMS].[dbo].[StudyCodeDetails] scd
INNER JOIN [dbo].[StudyCodeToMileStone] sc
ON scd.StudyCodeId = sc.StudyCodeId
) AS t1
CROSS APPLY (
SELECT pm.ProductName,
tm.TherapyName,
dm.Dosage,
stm.StudyType,
com.Condition,
cn.CountryName,
crm.CRO,
dsm.Design,
dtm.DesignTag,
ud.[user_name] AS 'RnD ProjManager',
udd.[user_name] AS 'Project Manager',
mm.MileStoneId,
mm.MileStoneName AS 'Milestone',
mm.Category AS 'Category',
FROM [dbo].[MileStoneMaster] mm
INNER JOIN dbo.ProductMaster pm ON scd.ProductId = pm.ProductId
INNER JOIN dbo.TherapyMaster tm ON tm.TherapyId = scd.TherapyId
INNER JOIN dbo.DosageMaster dm ON dm.DosageId = scd.DosageId
INNER JOIN dbo.CountryMaster cn ON cn.CountryId = scd.CountryId
INNER JOIN dbo.[User_Dtls] ud ON ud.Pk_ID = scd.RnDProjManagerId
INNER JOIN dbo.[User_Dtls] udd ON udd.Pk_ID = scd.ProjectManagerId
INNER JOIN dbo.CroMaster crm ON crm.CroId = scd.CRO
INNER JOIN dbo.DesignMaster dsm ON dsm.DesignId = scd.DesignId
INNER JOIN dbo.DesignTagMaster dtm ON dtm.DesignTagId = scd.DesignTagId
INNER JOIN dbo.StudyTypeMaster stm ON stm.StudyTypeId = scd.StudyTypeId
INNER JOIN dbo.ConditionMaster com ON com.ConditionId = scd.Condition
WHERE scd.StudyCodeId IN (
SELECT CAST(Item AS INTEGER)
FROM [dbo].[SplitString](#StudyCodeId, ',')
)
AND mm.[AdditionalPayment] = 0
AND mm.MileStoneId = t1.MileStoneId
ORDER BY mm.MileStoneId
) AS t2
) AS X
GROUP BY X.[IsActive]
--scd.[StudyCodeId]
,
X.[StudyCode],
X.[ProductName],
X.[TherapyName],
X.[Dosage],
X.[StudyType],
X.[Condition],
X.[CountryName],
X.[CRO],
X.[Design],
X.[DesignTag],
X.[RnD ProjManager],
X.[Project Manager],
X.[IPDFillingTimeline],
X.[Comments],
X.[MileStoneId],
X.[Milestone],
X.[Category],
X.[BaseLineDate],
X.[ActualDate]
END
I probably messed that title up! So I have a column called "programID" and I want another column to tell me the most recent date an order was placed using the programID. I think I'd need a subcolumn but the problem is how do I use the row's programID so that it matches the programID for the same row?
DECLARE #ClientIDs varchar(4) = 6653;
DECLARE #ProgramStatus char(1) = 'Y'; -- Y, N, or R
SELECT
rcp.RCPID AS ProgramID
, rcp.RCPName AS Program
, rcp.RCPActive AS ProgramStatus
, aa.AACustomCardInternalReview AS VCCP
, aa.AAJobNo AS AAJobNo
, aas.AASName AS AAStatus
, rcp.RCPOpsApproved AS OpsApproved
, clt.CltID AS ClientID
, rcp.RCPSignatureRequired AS SignatureRequired
, st.STEnumValue AS DefaultShipType
, rcp.RCPShipMethodOverrideType AS ShipTypeOverride
,aa.AANetworkProgramID
,(Select max(cdconfirmationdate) from carddet where ) --can't figure this part out
FROM
RetailerCardProgram rcp WITH (NOLOCK)
INNER JOIN ClientRetailerMap crm WITH (NOLOCK)
ON crm.CRMRetailerID = rcp.RCPRetailerID
INNER JOIN Client clt WITH(NOLOCK)
ON clt.CltID = crm.CRMCltID
LEFT JOIN AssociationApproval aa WITH (NOLOCK)
ON aa.AARetailerID = rcp.RCPRetailerID
AND aa.AABin = rcp.RCPBin6
AND aa.AAFrontOfPlasticTemplateID = rcp.RCPFOCTemplateID
AND aa.AABackOfPlasticTemplateID = rcp.RCPBOCTemplateID
AND ISNULL(aa.AACardID, 0) = ISNULL(rcp.RCPDefaultPlasticCardID, 0)
-- AND LOWER(rcp.RCPName) NOT LIKE '%do not use%' -- Needed for AA Job Number 1594
LEFT JOIN AssociationApprovalStatus aas WITH (NOLOCK)
ON aas.AASID = aa.AAAssociationApprovalStatusID
LEFT JOIN OpenLoopAssociation ola WITH (NOLOCK)
ON ola.OLAID=rcp.RCPOLAID
LEFT JOIN ClientCardProgramMap ccpm WITH (NOLOCK)
ON ccpm.CCPMCardProgramID = rcp.RCPID
AND ccpm.CCPMClientID = clt.CltID
LEFT JOIN TippingModule tm WITH (NOLOCK)
ON tm.TMid = rcp.RCPTippingModuleID
LEFT JOIN GiftCardTemplate fgt WITH (NOLOCK)
ON fgt.gtid = rcp.RCPFOCTemplateID
AND fgt.GTPage='P'
LEFT JOIN GiftCardTemplate bgt WITH (NOLOCK)
ON bgt.gtid = rcp.RCPBOCTemplateID
AND bgt.GTPage='PB'
LEFT JOIN Card c WITH (NOLOCK)
ON c.CardID = rcp.RCPDefaultCarrierID
LEFT JOIN CardType ct WITH (NOLOCK)
ON ct.CTID = c.CardTypeID
LEFT JOIN RetailerCardProgramTCSheetMap rtm1 WITH (NOLOCK)
ON rtm1.RTMRCPID = rcp.RCPID
AND rtm1.RTMInsertOrder = 1
LEFT JOIN RetailerCardProgramTCSheetMap rtm2 WITH (NOLOCK)
ON rtm2.RTMRCPID = rcp.RCPID
AND rtm2.RTMInsertOrder = 2
LEFT JOIN RetailerCardProgramTCSheetMap rtm3 WITH (NOLOCK)
ON rtm3.RTMRCPID = rcp.RCPID
AND rtm3.RTMInsertOrder = 3
LEFT JOIN RetailerCardProgramTCSheetMap rtm4 WITH (NOLOCK)
ON rtm4.RTMRCPID = rcp.RCPID
AND rtm4.RTMInsertOrder = 4
LEFT JOIN TCSheet i1 WITH (NOLOCK)
ON i1.TCSID = rtm1.RTMTCSID
LEFT JOIN TCSheet i2 WITH (NOLOCK)
ON i2.TCSID = rtm2.RTMTCSID
LEFT JOIN TCSheet i3 WITH (NOLOCK)
ON i3.TCSID = rtm3.RTMTCSID
LEFT JOIN TCSheet i4 WITH (NOLOCK)
ON i4.TCSID = rtm4.RTMTCSID
LEFT JOIN ShipType st WITH (NOLOCK)
ON st.STId = rcp.RCPDefaultShipTypeID
WHERE
clt.CltID IN (#ClientIDs) -- 6653 and 6657.
AND rcp.RCPActive IN (#ProgramStatus)
ORDER BY
AAJobNo
, Program
You want to join with a nested select on the table carddet. I'm inferring that RCPID is the relationship between carddet and your main table RetainerCardProgram...
SELECT rcp.RCPID AS ProgramID,
date.MAXDATE AS MaxDate,
rest of your columns...
FROM RetailerCardProgram rcp WITH (NOLOCK)
INNER JOIN (
SELECT RCPID, MAX(cdconfirmationdate) as 'MAXDATE'
FROM carddet
GROUP BY RCPID
) date on date.RCPID = rcp.RCPID
rest of query...
You may want a left join if not all IDs have a date in carddet.
Obligatory addition: Also your use of NOLOCK is a bit terrifying. See http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/