Tuning Slow Performing Queries - sql-server-2008

I have a query which is taking too long to execute.
I used database tuning advisor to check this query and it suggested some missing indexes and statistics. The problem is I can't create missing index and statistics on those tables because it will slowdown insert/update and affect other scripts. They can't sacrifice their scripts performance because of my query.
Without the help of DTA or disturbing other scripts how do I have to tune my query? Can i break it into small pieces? If so, how?
INSERT INTO #val
SELECT lid.orgid,
lid.periodid,
lid.sourceid,
lid.statementtypecode,
lid.financialsbucketid,
lid.statementcurrencycodeiso,
lid.lineitemid,
lll.financialconceptidglobal,
lid.physicalmeasureid,
CASE
WHEN EXISTS(SELECT TOP 1 '1'
FROM trf.dbo.lineitemfundbdescription LIFD(nolock)
WHERE lll.orgid = lifd.orgid
AND lll.lineitemid = lifd.lineitemid) THEN
(SELECT lifd.lineitemshortdescription
FROM trf.dbo.lineitemfundbdescription LIFD(nolock)
WHERE lll.orgid = lifd.orgid
AND lll.lineitemid = lifd.lineitemid)
ELSE lll.lineitemname
END AS LineItemName,
( CASE
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND
lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 1 ) THEN
lid.lineiteminstancevalue *
cds.dbo.Exrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso, p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'M' ) THEN lid.lineiteminstancevalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("MONTH", -p.periodlength, p.periodenddate), p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'W' ) THEN lid.lineiteminstancevalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("WEEK", -p.periodlength, p.periodenddate), p.periodenddate)
ELSE lid.lineiteminstancevalue
END ) AS LineItemInstanceValue,
( CASE
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 1 ) THEN
lid.adjustedforcorporateactionvalue *
cds.dbo.Exrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso, p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'M' ) THEN
lid.adjustedforcorporateactionvalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("MONTH", -p.periodlength, p.periodenddate), p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'W' ) THEN
lid.adjustedforcorporateactionvalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("WEEK", -p.periodlength, p.periodenddate), p.periodenddate)
ELSE lid.adjustedforcorporateactionvalue
END ) AS AdjustedForCorporateActionValue,
lid.reportedcurrencycodeiso,
lid.xbrlelementid,
xbrlele.xbrlelementname,
Cast(NULL AS CHAR(3)),
Cast(NULL AS DATETIME),
Cast(NULL AS DATETIME),
Cast(NULL AS CHAR(1)),
Cast(NULL AS DATETIME),
Cast(NULL AS SMALLINT),
src.dcn,
src.docformat,
lid.asreporteditemid,
ari.docbyteoffset,
ari.docbytelength,
ari.bookmark,
ari.itemdisplayednegativeflag,
ari.itemscalingfactor,
ari.itemdisplayedvalue,
ari.reportedvalue,
ari.reporteddescription,
ari.editeddescription,
src.documentid,
lid.isderived,
lid.statementsectioncode,
IsMissMatchPhysicalMeasureID =0,
lid.istotal,
lid.isexcludedfromstandardization,
si.isdetailed AS IsDetailedSection,
si.ispreliminary AS IsPreliminary,
IsCreditSection =Cast(NULL AS BIT),
IsCreditFCC =Cast(NULL AS BIT),
si.isproforma,
lll.instrumentndaid,
InterimTypeID = CASE p.periodicitycode
WHEN 'A' THEN 0
WHEN 'S' THEN 2
WHEN 'T' THEN 3
WHEN 'Q' THEN 4
END,
si.isnotcomparabletopriorperiod,
si.isfundbspecial,
si.isderived AS IsDerivedSI,
lid.systemderivedtypecode
--FBLog.tasktypeid,
--FBLog.systemstartdatetime,
--FBLog.issplit
FROM trf.dbo.lineiteminstance LID(nolock)
--INNER JOIN #fundbbackwardlog FBLog
-- ON FBLog.orgid = lid.orgid
-- AND FBLog.periodid = lid.periodid
-- AND FBLog.sourceid = lid.sourceid
-- AND FBLog.statementtypecode = lid.statementtypecode
-- AND FBLog.financialsbucketid = lid.financialsbucketid
-- AND FBLog.statementcurrencycodeiso =
-- lid.statementcurrencycodeiso
-- AND lid.asreporteditemid IS NOT NULL
-- AND lid.lineiteminstanceasreporteditemid IS NULL
INNER JOIN trf.dbo.statementinstance SI(nolock)
ON lid.orgid = si.orgid
AND lid.periodid = si.periodid
AND lid.sourceid = si.sourceid
AND lid.statementtypecode = si.statementtypecode
AND lid.financialsbucketid = si.financialsbucketid
AND lid.statementcurrencycodeiso = si.statementcurrencycodeiso
INNER JOIN trf.dbo.period P(nolock)
ON lid.orgid = p.orgid
AND lid.periodid = p.periodid
INNER JOIN trf.dbo.lineitem LLL(nolock)
ON lll.orgid = lid.orgid
AND lll.lineitemid = lid.lineitemid
INNER JOIN trf.dbo.financialconcept FC(nolock)
ON lll.financialconceptidglobal = fc.financialconceptid
LEFT OUTER JOIN trf.dbo.xbrlelement XBRLEle(nolock)
ON lid.xbrlelementid = xbrlele.xbrlelementid
INNER JOIN trf.dbo.asreportedinstance ARI(nolock)
ON lid.orgid = ari.orgid
AND lid.sourceid = ari.sourceid
AND lid.asreporteditemid = ari.asreporteditemid
INNER JOIN trf.dbo.[source] SRC(nolock)
ON src.orgid = ari.orgid
AND src.sourceid = ari.sourceid
WHERE ari.reportedvalue IS NOT NULL --AND SRC.DCN > '' --AND SRC.DocFormat > '' --AND ARI.BookMark > ''

Try to remove functions called in the query like : Exrate() and Getaveragefxrate().
Also change the case statement, where you are using subquery as following.
In the end of the query, use
left outer join trf.lineitemfundbdescription lifd
on lll.orgid = lifd.orgid and lll.lineitemid = lifd.lineitemid
and then the case will be changed to
case
when lifd.orgid is null then lll.lineitemname
else lifd.lineitemshortdescription End As LineItemName
It will fine tune your query to a level and gives you a correct execution plan and advice accordingly.
Remember that execution plan does not show the plan of user defined functions called with in the query.

Related

MySQL query case statement in where optimization

I am writing a query in mysql i am not familer with the recursive query to much.
how and what i need to do to optimization of the below query as the conditions i put not looks good ,there must be a easier way to do same.
select
b.entity_id
from
entity_hierarchies a,
entity_hierarchies b
where
a.entity_id = 25
and a.entity_type = 'user'
and b.entity_type = 'idea'
and a.Geography_Geography =
case
when
a.Geography_Geography is null
then
a.Geography_Geography
else
b.Geography_Geography
end
and COALESCE(a.Geography_Country, '') =
case
when
a.Geography_Country is null
then
COALESCE(a.Geography_Country, '')
else
b.Geography_Country
end
and COALESCE(a.Geography_DistrictOrCounty, '') =
case
when
a.Geography_DistrictOrCounty is null
then
COALESCE(a.Geography_DistrictOrCounty, '')
else
b.Geography_DistrictOrCounty
end
and COALESCE(a.Geography_State, '') =
case
when
a.Geography_State is null
then
COALESCE(a.Geography_State, '')
else
b.Geography_State
end
and COALESCE(a.Geography_City, '') =
case
when
a.Geography_City is null
then
COALESCE(a.Geography_City, '')
else
b.Geography_City
end
Intro
I noticed you could rewrite some of these statements in a much simpler form.
So for example:
and a.Geography_Geography =
case
when
a.Geography_Geography is null
then
a.Geography_Geography
else
b.Geography_Geography
end
can simply become:
AND ( a.Geography_Geography is null or a.Geography_Geography = b.Geography_Geography )
Final Solution
select
b.entity_id
from
entity_hierarchies a,
entity_hierarchies b
where
a.entity_id = 25
and a.entity_type = 'user'
and b.entity_type = 'idea'
AND ( a.Geography_Geography is null OR a.Geography_Geography = b.Geography_Geography )
AND ( a.Geography_Country is null OR a.Geography_Geography = b.Geography_Country )
AND ( a.Geography_DistrictOrCounty is null OR a.Geography_DistrictOrCounty = b.Geography_DistrictOrCounty )
AND ( a.Geography_State is null OR a.Geography_State = b.Geography_State )
AND ( a.Geography_City is null OR a.Geography_City = b.Geography_City );

Any other way to perform joins on same column?

I was just rewriting my question as this answer wont work for me. I have a stored procedure as follows:
--GetAllFilteredProjects
Alter PROCEDURE [GetAllFilteredProjects]
#UserId Int,
#ServerGroupId int,
#ProjectIDs UDT_ProjectIDs Readonly,
#ProjectDesc NVARCHAR(2000),
#TopRecords INT,
#StartProjectID INT,
#CustomerGroupId INT,
#SearchStates dbo.[UDT_SearchStates] Readonly
AS
BEGIN
SET NOCOUNT ON;
DECLARE #StartProjectNumber INT
DECLARE #AcceptUnAcceptFilterNumberv INT
DECLARE #IgnoreRestrictedNumberv INT
DECLARE #SearchProjectIDsCount INT
DECLARE #SearchProjectDesc VARCHAR
SET #IgnoreRestrictedNumberv=0
SET #AcceptUnAcceptFilterNumberv =0
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('StartProjectIDFilter')
where USERID = #UserId
SET #ProjectDesc = REPLACE(#ProjectDesc, '*', '%')
SET #ProjectDesc = REPLACE(#ProjectDesc, '?', '_')
Print(#ProjectDesc)
Select #SearchProjectIDsCount=count(*) from #ProjectIDs;
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterUnAccept','ProjectFilterAccept')
where USERID = #UserId
IF(#AcceptUnAcceptFilterNumberv = 1)
BEGIN
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterAccept')
where USERID = #UserId
IF #AcceptUnAcceptFilterNumberv = 0
BEGIN
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterUnAccept')
where USERID = #UserId
IF(#AcceptUnAcceptFilterNumberv = 1) -- UnAccepted
BEGIN
SET #AcceptUnAcceptFilterNumberv = 3
END
END
END
select #IgnoreRestrictedNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterIgnoreRestricted')
where USERID = #UserId
IF OBJECT_ID('TEMPDB..#PROJECTS') IS NOT NULL DROP TABLE #PROJECTS
CREATE TABLE #PROJECTS
(
TMP_PROJECT_ID INT,
TMP_SERVERGROUP_ID INT,
TMP_DESCRIPTION NVARCHAR(1000),
TMP_PROJECT_STATE_ID INT,
TMP_ACCEPTED_STATE_ID INT,
TMP_ISRESTRICTED_ID INT
)
IF OBJECT_ID('TEMPDB..#SELECTED_STATES') IS NOT NULL DROP TABLE #SELECTED_STATES
CREATE TABLE #SELECTED_STATES
(
TMP_PREFSET_STATEID INT
)
-- All the project accepted for server group and unaccepted for server group which are promoted to
-- Validation or Pilot or Factory states
IF #IgnoreRestrictedNumberv=1
BEGIN
INSERT INTO #PROJECTS
SELECT p.projectid,servergroupid,p.description,p.StateId AS ProjectState, pa.stateid ,p.IsRestricted
FROM v_Project p left outer join ProjectAcception pa ON p.ProjectId = pa.ProjectId and pa.ServerGroupId=#ServerGroupId
WHERE P.CustomerGroupId = #CustomerGroupId AND P.StateId IN(Select StateID From #SearchStates) and P.StateId in (select ss.AFPStateId from ServerGroupStateSettings ss where ss.servergroupid=#ServerGroupId)
--added by shankar, regarding the filtering functionality
--in projects tab of a server group
and (#SearchProjectIDsCount =0 Or p.projectid in
(1673))
AND (Upper(p.Description) LIKE '%' +Upper(#ProjectDesc) + '%')
AND p.projectid>=#StartProjectID
AND p.IsRestricted = 0
END
ELSE
BEGIN
INSERT INTO #PROJECTS
SELECT p.projectid,servergroupid,p.description,p.StateId AS ProjectState, pa.stateid ,p.IsRestricted
FROM v_Project p left outer join ProjectAcception pa ON p.ProjectId = pa.ProjectId and pa.ServerGroupId=#ServerGroupId
WHERE P.CustomerGroupId = #CustomerGroupId AND P.StateId IN(Select StateID From #SearchStates) and P.StateId in (select ss.AFPStateId from ServerGroupStateSettings ss where ss.servergroupid=#ServerGroupId)
--added by shankar, regarding the filtering functionality
--in projects tab of a server group
and (#SearchProjectIDsCount =0 Or p.projectid in
(1673))
AND (Upper(p.Description) LIKE '%' +Upper(#ProjectDesc) + '%')
AND p.projectid>=#StartProjectID
END
-- State selected by user to filter the projects
INSERT INTO #SELECTED_STATES
select ap.AFPStateId
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
inner join AFPState ap on 'ProjectFilter' + ap.AFPStateDesc = PropertyName
where USERID = #UserId
IF #AcceptUnAcceptFilterNumberv = 1 -- Accepted
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case [1] when 2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM, #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID IN
(
SELECT DISTINCT #PROJECTS.TMP_PROJECT_ID
FROM #PROJECTS
GROUP BY #PROJECTS.TMP_PROJECT_ID HAVING MAX(#PROJECTS.TMP_ACCEPTED_STATE_ID) IN
--WHERE #PROJECTS.TMP_ACCEPTED_STATE_ID IN
(
SELECT #SELECTED_STATES.TMP_PREFSET_STATEID
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
ELSE IF #AcceptUnAcceptFilterNumberv = 2 -- Both
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case
when [1]=2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM , #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID in
(
SELECT DISTINCT PJ.TMP_PROJECT_ID
FROM #PROJECTS PJ
--WHERE isnull(PJ.TMP_ACCEPTED_STATE_ID,0) <=
GROUP BY PJ.TMP_PROJECT_ID HAVING MAX(isnull(PJ.TMP_ACCEPTED_STATE_ID,0)) <=
(
SELECT max(#SELECTED_STATES.TMP_PREFSET_STATEID)
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
ELSE IF #AcceptUnAcceptFilterNumberv = 3 -- UnAccepted
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case [1] when 2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM , #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID IN
(
SELECT DISTINCT p.TMP_PROJECT_ID
FROM #PROJECTS p
WHERE (SELECT max(ISNULL(PJ.TMP_ACCEPTED_STATE_ID,0))
FROM #PROJECTS PJ
GROUP BY PJ.TMP_PROJECT_ID HAVING PJ.TMP_PROJECT_ID = p.TMP_PROJECT_ID
) <
(
SELECT MAX(#SELECTED_STATES.TMP_PREFSET_STATEID)
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
END
Now while inserting values into my table projects I have a condition where p.IsRestrictedID=0.
Here I have one more thing which I need to consider. I need to insert the projects which have IsRestricted=1 where this could be executed when this statement returns 1
SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId
Means I need to consider the project which has IsRestricted=1 when the above select query returns 1.
I wanted to add this to that Insert into project query.
How can I do that?
Just add the prefix of the table alias every place you use the column name, to prevent the ambiguous column error:
SELECT
p.projectid,
pa.servergroupid, -- Here I added "pa." as a prefix
p.description,
. . .
I got the solution for this I just need to add an OR condition while inserting Projects.
The modified one is as follows:
--GetAllFilteredProjects
Alter PROCEDURE [GetAllFilteredProjects]
#UserId Int,
#ServerGroupId int,
#ProjectIDs UDT_ProjectIDs Readonly,
#ProjectDesc NVARCHAR(2000),
#TopRecords INT,
#StartProjectID INT,
#CustomerGroupId INT,
#SearchStates dbo.[UDT_SearchStates] Readonly
AS
BEGIN
SET NOCOUNT ON;
DECLARE #StartProjectNumber INT
DECLARE #AcceptUnAcceptFilterNumberv INT
DECLARE #IgnoreRestrictedNumberv INT
DECLARE #SearchProjectIDsCount INT
DECLARE #SearchProjectDesc VARCHAR
SET #IgnoreRestrictedNumberv=0
SET #AcceptUnAcceptFilterNumberv =0
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('StartProjectIDFilter')
where USERID = #UserId
SET #ProjectDesc = REPLACE(#ProjectDesc, '*', '%')
SET #ProjectDesc = REPLACE(#ProjectDesc, '?', '_')
Print(#ProjectDesc)
Select #SearchProjectIDsCount=count(*) from #ProjectIDs;
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterUnAccept','ProjectFilterAccept')
where USERID = #UserId
IF(#AcceptUnAcceptFilterNumberv = 1)
BEGIN
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterAccept')
where USERID = #UserId
IF #AcceptUnAcceptFilterNumberv = 0
BEGIN
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterUnAccept')
where USERID = #UserId
IF(#AcceptUnAcceptFilterNumberv = 1) -- UnAccepted
BEGIN
SET #AcceptUnAcceptFilterNumberv = 3
END
END
END
select #IgnoreRestrictedNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterIgnoreRestricted')
where USERID = #UserId
IF OBJECT_ID('TEMPDB..#PROJECTS') IS NOT NULL DROP TABLE #PROJECTS
CREATE TABLE #PROJECTS
(
TMP_PROJECT_ID INT,
TMP_SERVERGROUP_ID INT,
TMP_DESCRIPTION NVARCHAR(1000),
TMP_PROJECT_STATE_ID INT,
TMP_ACCEPTED_STATE_ID INT,
TMP_ISRESTRICTED_ID INT
)
IF OBJECT_ID('TEMPDB..#SELECTED_STATES') IS NOT NULL DROP TABLE #SELECTED_STATES
CREATE TABLE #SELECTED_STATES
(
TMP_PREFSET_STATEID INT
)
-- All the project accepted for server group and unaccepted for server group which are promoted to
-- Validation or Pilot or Factory states
IF #IgnoreRestrictedNumberv=1
BEGIN
INSERT INTO #PROJECTS
SELECT p.projectid, servergroupid,p.description,p.StateId AS ProjectState, pa.stateid ,p.IsRestricted
FROM v_Project p left outer join ProjectAcception pa ON p.ProjectId = pa.ProjectId and pa.ServerGroupId=#ServerGroupId
WHERE P.CustomerGroupId = #CustomerGroupId AND P.StateId IN(Select StateID From #SearchStates) and P.StateId in (select ss.AFPStateId from ServerGroupStateSettings ss where ss.servergroupid=#ServerGroupId)
--added by shankar, regarding the filtering functionality
--in projects tab of a server group
and (#SearchProjectIDsCount =0 Or p.projectid in
(1673))
AND (Upper(p.Description) LIKE '%' +Upper(#ProjectDesc) + '%')
AND p.projectid>=#StartProjectID
AND p.IsRestricted = 0
OR p.IsRestricted IN (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = p.projectid AND PR.ServerGroupId = #ServerGroupId )
END
ELSE
BEGIN
INSERT INTO #PROJECTS
SELECT p.projectid,servergroupid,p.description,p.StateId AS ProjectState, pa.stateid ,p.IsRestricted
FROM v_Project p left outer join ProjectAcception pa ON p.ProjectId = pa.ProjectId and pa.ServerGroupId=#ServerGroupId
WHERE P.CustomerGroupId = #CustomerGroupId AND P.StateId IN(Select StateID From #SearchStates) and P.StateId in (select ss.AFPStateId from ServerGroupStateSettings ss where ss.servergroupid=#ServerGroupId)
--added by shankar, regarding the filtering functionality
--in projects tab of a server group
and (#SearchProjectIDsCount =0 Or p.projectid in
(1673))
AND (Upper(p.Description) LIKE '%' +Upper(#ProjectDesc) + '%')
AND p.projectid>=#StartProjectID
END
-- State selected by user to filter the projects
INSERT INTO #SELECTED_STATES
select ap.AFPStateId
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
inner join AFPState ap on 'ProjectFilter' + ap.AFPStateDesc = PropertyName
where USERID = #UserId
IF #AcceptUnAcceptFilterNumberv = 1 -- Accepted
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case [1] when 2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM, #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID IN
(
SELECT DISTINCT #PROJECTS.TMP_PROJECT_ID
FROM #PROJECTS
GROUP BY #PROJECTS.TMP_PROJECT_ID HAVING MAX(#PROJECTS.TMP_ACCEPTED_STATE_ID) IN
--WHERE #PROJECTS.TMP_ACCEPTED_STATE_ID IN
(
SELECT #SELECTED_STATES.TMP_PREFSET_STATEID
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
ELSE IF #AcceptUnAcceptFilterNumberv = 2 -- Both
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case
when [1]=2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM , #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID in
(
SELECT DISTINCT PJ.TMP_PROJECT_ID
FROM #PROJECTS PJ
--WHERE isnull(PJ.TMP_ACCEPTED_STATE_ID,0) <=
GROUP BY PJ.TMP_PROJECT_ID HAVING MAX(isnull(PJ.TMP_ACCEPTED_STATE_ID,0)) <=
(
SELECT max(#SELECTED_STATES.TMP_PREFSET_STATEID)
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
ELSE IF #AcceptUnAcceptFilterNumberv = 3 -- UnAccepted
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case [1] when 2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM , #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID IN
(
SELECT DISTINCT p.TMP_PROJECT_ID
FROM #PROJECTS p
WHERE (SELECT max(ISNULL(PJ.TMP_ACCEPTED_STATE_ID,0))
FROM #PROJECTS PJ
GROUP BY PJ.TMP_PROJECT_ID HAVING PJ.TMP_PROJECT_ID = p.TMP_PROJECT_ID
) <
(
SELECT MAX(#SELECTED_STATES.TMP_PREFSET_STATEID)
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
END

change this condition using join in sql

I need to use join instead of this query with same condition
select (
(
select
case when sum(A.[Quantity]) is null then 0 else sum(A.[Quantity]) END
from [tablename1] A
where ((A.[Status]=4) AND (A.[Spcl Order]=1) AND (A.[Finished Date] = aa.FromDate ))
)
+
(
select
case when sum(A.[Quantity]) is null then 0 else sum(A.[Quantity]) END
from [tablename2] A
where ((A.[Item Category Code] = 'STYLES') AND (A.[Prod_ Order No_]='') AND
( A.[Buy-from Vendor No_] in (#vendor)) AND (A.[Quantity]>0) AND
(A.[Spcl Order]= 1) AND ( A.[Posting Date] = aa.FromDate))
)
)

How to perform multiple calculations with in a single query

I have a situation where in i have to get the data from an Year Ago , Previous Month and Current Month. What is the best way to achieve this ?
I have a table which contains the year,month and data in it. In the below query have added a filter
c.ReportMonth = DATENAME(month, #12MonthsAgo) and c.ReportYear = Year(#12MonthsAgo)
This is for an year ago. In the same way if i have to get the previous month and current month, can i do that with in the same query by setting the filters ? how do we do that ?
Is there a better way other than i end up writing 3 select queries and then putting the select to a tmp table and later merging the tables ?
create table #TPTABLE
(
KPIName varchar(150)
,MetricName Varchar(200)
,MetricId INT
,DataSource varchar(50)
,[AnYearAgo] Float
,[PreviousMonth] float
,[CurrentMonth] float
);
insert into #TPTABLE
(KPIName,MetricName,MetricId,DataSource,[AnYearAgo])
SELECT
p.KPIName
,p.MetricName
,p.MetricId
,p.DataSource
,c.Value as [AnYearAgo]
FROM [IntegratedCare].[report].[KPIMetricDetails] p
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c
ON p.[MetricId] = c.MetricId
WHERE c.ReportMonth = DATENAME(month, #12MonthsAgo) and c.ReportYear = Year(#12MonthsAgo)
ORDER BY KPI_Id ASC, [MetricId] ASC
SELECT
p.KPIName
,p.MetricName
,p.MetricId
,p.DataSource
,c.Value
,c2.Value
,c3.Value
FROM [IntegratedCare].[report].[KPIMetricDetails] p
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c
ON p.[MetricId] = c.MetricId
AND c.[CommissionerCode] = COALESCE(NULLIF(#Commissioner, ''), c.[CommissionerCode])
ANd ReportMonth = DATENAME(month, #12MonthsAgo) and c.ReportYear = Year(#12MonthsAgo)
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c2
ON p.[MetricId] = c2.MetricId
AND c2.[CommissionerCode] = COALESCE(NULLIF(#Commissioner, ''), c2.[CommissionerCode])
ANd c2.ReportMonth = DATENAME(month, #PreviousMonth) and c2.ReportYear = Year(#PreviousMonth)
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c3
ON p.[MetricId] = c3.MetricId
AND c3.[CommissionerCode] = COALESCE(NULLIF(#Commissioner, ''), c3.[CommissionerCode])
ANd c3.ReportMonth = DATENAME(month, #PreviousMonth) and c3.ReportYear = Year(#PreviousMonth)
ORDER BY p.KPI_Id ASC, p.[MetricId] ASC
I think what you need is this:
insert into #TPTABLE
(KPIName,MetricName,MetricId,DataSource,[AnYearAgo])
SELECT
KPIName
,MetricName
,MetricId
,DataSource
,[AnYearAgo]
,[PreviousMonth]
,[CurrentMonth]
FROM (
SELECT
KPIName
,MetricName
,MetricId
,DataSource
,KPI_Id
,sum(case when c.ReportMonth = DATENAME(month, #12MonthsAgo) and c.ReportYear = Year(#12MonthsAgo) then c.Value else 0 end) as [AnYearAgo]
,sum(case when c.ReportMonth = DATENAME(month, #PreviousMonth) and c.ReportYear = Year(#PreviousMonth) then c.Value else 0 end) as [PreviousMonth]
,sum(case when c.ReportMonth = DATENAME(month, #CurrentMonth) and c.ReportYear = Year(#CurrentMonth) then c.Value else 0 end) as [CurrentMonth]
FROM [IntegratedCare].[report].[KPIMetricDetails] p
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c
ON p.[MetricId] = c.MetricId
GROUP BY KPIName, MetricName, MetricId, DataSource, KPI_Id
ORDER BY KPI_Id ASC, [MetricId] ASC

SQL Subquery Questions

I am trying to combine these 2 queries in such a way to determine who the PI is that owns equipment (>$100K value). I have the ability to find all the equipment one PI owns that is greater then 100k. I also have the ability to see all the PIs. I just cannot get these 2 queries to combine. I have tried with a WHERE subquery and an EXIST subquery. I want to be able to find all the equipment (matched with its PI owner) where the PI exists in query #2.
Query #1 for finding equipment of a specific PI
select Account_No,Inventory_No,Building_No,Room_No,CDDEPT,Location,Normalized_MFG,Manufacturer_Name,Normalized_Model,Name,Serial_Code,CONCAT( '$', FORMAT( Cost, 2 ) ) as Cost, Equipment_Inventory_Normalized.Active
from Temp_Equipment_Inventory.Equipment_Inventory_Normalized, `paul`.`ROOM`, `paul`.`BLDG`, `paul`.`LABORATORY`, `paul`.`PERSON`
where (`PERSON`.`ID` = `LABORATORY`.`PI_ID` OR `PERSON`.`ID` = `LABORATORY`.`SUPV_ID`)
AND `LABORATORY`.`RM_ID` = `ROOM`.`ID`
AND `LABORATORY`.`ACTIVE` = '1'
AND `ROOM`.`BLDG_ID` = `BLDG`.`ID`
AND ((
`BLDG`.`BLDGNUM` = Equipment_Inventory_Normalized.Building_No
AND Equipment_Inventory_Normalized.Actual_Building IS NULL
AND (`BLDG`.`BLDGNUM` != '1023' AND `LABORATORY`.`OTHER_LEVEL` != '1' AND `ROOM`.`RMNUM` != '0199')
)OR (
`BLDG`.`BLDGNUM` = Equipment_Inventory_Normalized.Actual_Building AND
(`BLDG`.`BLDGNUM` != '1023' AND `LABORATORY`.`OTHER_LEVEL` != '1' AND `ROOM`.`RMNUM` != '0199')
))
AND ((
`ROOM`.`RMNUM` = Equipment_Inventory_Normalized.Room_No
AND Equipment_Inventory_Normalized.Actual_Room IS NULL
)OR (
`ROOM`.`RMNUM` = Equipment_Inventory_Normalized.Actual_Room
))
AND Equipment_Inventory_Normalized.Active !=0
AND SurplusPending != '1'
AND Cost >= 100000
AND `PERSON`.`CANNUM`='810010787'
Query 2 that finds all the PIs
select distinct i.CAN
from CGWarehouse.CCGV10WC w
inner join CGWarehouse.CCGV10IC i
on w.PROJECT_NUMBER=i.SPONSORED_PROJECT
and w.SEQUENCE_NUMBER=i.PROJECT_SEQUENCE
where w.STATUS='A'
and i.PRIN_INVEST_CODE='Y'
and i.DEL_CODE!='Y'
and i.CAN IS NOT NULL
Perhaps you're looking for the IN keyword in your WHERE clause?
Forgive me, but I had to clean up the formatting of your query a little...it's kinda my OCD thing:
SELECT
Account_No,
Inventory_No,
Building_No,
Room_No,
CDDEPT,
Location,
Normalized_MFG,
Manufacturer_Name,
Normalized_Model,
Name,
Serial_Code,
CONCAT('$', FORMAT( Cost, 2 )) AS Cost,
Equipment_Inventory_Normalized.Active
FROM
Temp_Equipment_Inventory.Equipment_Inventory_Normalized a,
`paul`.`ROOM`,
`paul`.`BLDG`,
`paul`.`LABORATORY`,
`paul`.`PERSON`
WHERE
(`PERSON`.`ID` = `LABORATORY`.`PI_ID` OR `PERSON`.`ID` = `LABORATORY`.`SUPV_ID`)
AND `LABORATORY`.`RM_ID` = `ROOM`.`ID`
AND `LABORATORY`.`ACTIVE` = '1'
AND `ROOM`.`BLDG_ID` = `BLDG`.`ID`
AND (
(
`BLDG`.`BLDGNUM` = Equipment_Inventory_Normalized.Building_No
AND Equipment_Inventory_Normalized.Actual_Building IS NULL
AND `BLDG`.`BLDGNUM` != '1023'
AND `LABORATORY`.`OTHER_LEVEL` != '1'
AND `ROOM`.`RMNUM` != '0199'
) OR (
`BLDG`.`BLDGNUM` = Equipment_Inventory_Normalized.Actual_Building
AND `BLDG`.`BLDGNUM` != '1023'
AND `LABORATORY`.`OTHER_LEVEL` != '1'
AND `ROOM`.`RMNUM` != '0199'
)
)
AND (
(
`ROOM`.`RMNUM` = Equipment_Inventory_Normalized.Room_No
AND Equipment_Inventory_Normalized.Actual_Room IS NULL
) OR (
`ROOM`.`RMNUM` = Equipment_Inventory_Normalized.Actual_Room
)
)
AND Equipment_Inventory_Normalized.Active !=0
AND SurplusPending != '1'
AND Cost >= 100000
AND `PERSON`.`CANNUM` IN ( /* this assumes that the `PERSON`.`CANNUM` column matches up with the CGWarehouse.CCGV10IC.CAN column */
SELECT DISTINCT i.CAN
FROM
CGWarehouse.CCGV10WC w
INNER JOIN CGWarehouse.CCGV10IC i ON w.PROJECT_NUMBER=i.SPONSORED_PROJECT AND w.SEQUENCE_NUMBER=i.PROJECT_SEQUENCE
WHERE
w.STATUS='A'
AND i.PRIN_INVEST_CODE='Y'
AND i.DEL_CODE!='Y'
AND i.CAN IS NOT NULL
)