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 );
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
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
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
)