Any other way to perform joins on same column? - sql-server-2008

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

Related

How to hide a column in output result in Mysql?

select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
if(finish_position = 1 , #b:=#b+1,#b:=#b) opening_position,
if(finish_position = 1 , #last_op:=official_rating,#last_op:=#last_op)last_opening_position,
cast(if(#b = 0 or finish_position = 1,0,#last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select #b:=0, #last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
I want to hide
opening_position, last_opening_position
columns from the output result. My Mysql version 8.0.18
Use a subquery
select sf_name,finish_position,official_rating,date,bsp,diff from
(
select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
if(finish_position = 1 , #b:=#b+1,#b:=#b) opening_position,
if(finish_position = 1 , #last_op:=official_rating,#last_op:=#last_op)last_opening_position,
cast(if(#b = 0 or finish_position = 1,0,#last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select #b:=0, #last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
)A
select historic_betfair_win_prices.sf_name,
historic_runners.finish_position,
historic_runners.official_rating,
historic_betfair_win_prices.date,
historic_betfair_win_prices.bsp,
cast(if((#b := if(finish_position = 1 ,
#b+1,
#b))= 0 or finish_position = 1,
0,
(#last_op := if(finish_position = 1 ,
official_rating,
#last_op)) - official_rating) as decimal(10,2)) difffrom historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select #b:=0, #last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50

Drop down parameter to restrict dataset on a column not in resultset

I have an SSRS report based upon a dataset. In the datasets query my where clause looks something like this
TM.term_grp_id in (SELECT distinct term_grp_id from ig_mrvCustomisations.dbo.vw_TerminalsByProfitCentre WHERE store_name = #STORENAME))
If I run the report without any further development, I won't be prompted for the #STORENAME value.
Instead, I manually created a parameter and tried to link it to the above value, but because I do not include the store_name value in my resultset, it seems i was unable to restrict on it.
I have created a drop down parameter in SSRS based upon the distinct values in the table above, but I am unable to tie them together.
How do I create a prompt that will restrict on #STORENAME ?
Full Query:
--DECLARE #STARTDATE DATETIME
--DECLARE #ENDDATE DATETIME
DECLARE #STORENAME NVARCHAR(800)
--SET #STARTDATE = GETDATE()-1 + '06:00:00:000'
--SET #ENDDATE = GETDATE() + '05:59:59:997'
SET #STORENAME = 'IVY'
select
(DATENAME(dw,GETDATE()-1 + '06:00:00:000')) as 'Day',
CONVERT(date,GETDATE()-1 + '06:00:00:000') as 'Date',
one.term_grp_name AS 'Terminal Group Name',
one.check_type_name AS 'Check Type Name',
(CASE WHEN LEFT(one.check_type_name,2) = 'EV' THEN 'Y' ELSE 'N' END) AS 'Event?',
LEFT(one.revenue_category_name,5) AS 'T3 Coding',
(CASE WHEN LEFT(one.revenue_category_name,2) = '71' THEN '99500'
WHEN LEFT(one.revenue_category_name,2) = '72' THEN '99550'
ELSE '99600' END) AS 'T3 Coding for comps',
LEFT(one.term_grp_name,4) AS 'Department',
(CASE WHEN LEFT(one.revenue_category_name,2) = '71' THEN 1010
WHEN LEFT(one.revenue_category_name,2) = '72' THEN 1020
WHEN LEFT(one.revenue_category_name,5) = '77700' THEN 1070
WHEN LEFT(one.revenue_category_name,5) = '77750' THEN 6165
ELSE 1090 END) as 'Account',
(CASE WHEN one.revenue_category_name = '' THEN 'Total' ELSE one.revenue_category_name END) AS 'Lookup',
LEFT(one.term_grp_name,4) + ' ' +
(CASE WHEN one.revenue_category_name = '' THEN 'Total' ELSE one.revenue_category_name END) AS 'Dept/Lookup',
one.revenue_category_name as 'Revenue Category',
sum(CONVERT(money,one.Tax)) + sum(CONVERT(money,one.NetRev)) + sum(CONVERT(money,one.Grat)) AS 'Net Tender',
sum(CONVERT(money,one.NetRev)) as 'Net Revenue',
sum(CONVERT(money,one.disc)) as 'Discount',
sum(CONVERT(money,one.gross)) as 'Gross Revenue',
(CASE WHEN LEFT(check_type_name,2) = 'EV' THEN 0 ELSE sum(CONVERT(money,one.gross)) END) as 'Gross Rev (excl Events)',
(CASE WHEN LEFT(check_type_name,2) = 'EV' THEN 0 ELSE SUM(CONVERT(MONEY,one.grat)) END) AS 'Gratuity (excl Events)',
(CASE WHEN LEFT(check_type_name,2) = 'EV' THEN 0 ELSE SUM(CONVERT(MONEY,one.tax)) END) AS 'Tax (excl Events)',
sum(CONVERT(money,one.Tax)) as 'Tax',
sum(CONVERT(money,one.Grat)) as 'Gratuity',
sum(CONVERT(money,one.SC)) as 'Service Charge',
sum(CONVERT(money,one.Tip)) as 'Tip',
sum(CONVERT(money,one.Covers)) as 'Covers',
Sum(CONVERT(decimal(30,2),one.avecover)) as 'Average Cover',
sum(CONVERT(money,one.Checks)) as 'Checks',
CONVERT(decimal(30,2),(sum(one.NetRev) / nullif(sum(one.Checks),0))) as 'Average Check'
from
(select
sum(CSD.sales_gross_amount - CSD.discount_amount) as 'NetRev',
sum(CSD.sales_gross_amount) as Gross,
sum(CSD.discount_amount) as Disc,
sum(CSD.gratuity_amount) as Grat,
sum(CSD.service_charge_amount) as SC,
sum(CSD.tip_amount) as Tip,
sum(CSD.tax_amount) as Tax,
sum(CSD.num_covers) as Covers,
(sum(CSD.sales_gross_amount - CSD.discount_amount) / nullif(sum(CSD.num_covers),0)) as 'AveCover',
0 as Checks,
'' as revenue_category_name,
TGM.term_grp_name,
CTD.check_type_name
from ig_business..Check_Sales_Detail CSD (NoLock)
join it_cfg..Terminal_Master TM (NoLock) on TM.term_id = CSD.tendered_terminal_id
join it_cfg..Term_Grp_Master TGM (NoLock) on TGM.term_grp_id = TM.term_grp_id and TGM.ent_id = 1
join ig_dimension..Check_Type_Dimension CTD (NoLock) on CTD.check_type_dim_id = CSD.check_type_dim_id
where CSD.transaction_data_id in
(select transaction_data_id
from ig_business..Check_Sales_Detail CSD (NoLock)
join it_cfg..Terminal_Master TM on TM.term_id = CSD.tendered_terminal_id
where tendered_date_time between GETDATE()-1 + '06:00:00:000' and GETDATE() + '05:59:59:997'
and TM.term_grp_id in (SELECT distinct term_grp_id from ig_mrvCustomisations.dbo.vw_TerminalsByProfitCentre WHERE store_name = #STORENAME))
and CSD.tendered_terminal_id <> 0
and CSD.void_state <> 2
group by TGM.term_grp_name, CTD.check_type_name
union all
select
sum(CRC.gross_sales_amount_tax_included - CRC.discount_amount_tax_included) as 'NetRev',
sum(CRC.gross_sales_amount_tax_included) as Gross,
sum(CRC.discount_amount_tax_included) as Disc,
0 as Grat,
0 as SC,
0 as Tip,
0 as Tax,
0 as Covers,
0 as 'AveCover',
0 as Checks,
RCD.revenue_category_name,
TGM.term_grp_name,
CTD.check_type_name
from
ig_business..Check_Revenue_Category_Detail CRC (NoLock)
join ig_dimension..Revenue_Category_Dimension RCD (NoLock) on RCD.revenue_category_dim_id = CRC.revenue_category_dim_id
left join ig_business..Check_Sales_Detail CSD (NoLock) on CRC.transaction_data_id = CSD.transaction_data_id
join it_cfg..Terminal_Master TM (NoLock) on CSD.tendered_terminal_id = TM.term_id
join it_cfg..Term_Grp_Master TGM (NoLock) on TGM.term_grp_id = TM.term_grp_id and TGM.ent_id = 1
join ig_dimension..Check_Type_Dimension CTD (NoLock) on CTD.check_type_dim_id = CSD.check_type_dim_id
where CRC.transaction_data_id in (select transaction_data_id
from ig_business..Check_Sales_Detail CSD (NoLock)
join it_cfg..Terminal_Master TM on TM.term_id = CSD.tendered_terminal_id
where tendered_date_time between GETDATE()-1 + '06:00:00:000' and GETDATE() + '05:59:59:997'
and TM.term_grp_id in (SELECT distinct term_grp_id from ig_mrvCustomisations.dbo.vw_TerminalsByProfitCentre WHERE store_name = #STORENAME))
Group By
RCD.revenue_category_name,
TGM.term_grp_name,
CTD.check_type_name
union all
select
0 as 'NetRev',
0 as Gross,
0 as Disc,
0 as Grat,
0 as SC,
0 as Tip,
0 as Tax,
0 as Covers,
0 as 'AveCover',
COUNT(distinct(CSD.check_number))as Checks,
'' as revenue_category_name,
TGM.term_grp_name,
CTD.check_type_name
from ig_business..Check_Sales_Detail CSD (NoLock)
join it_cfg..Terminal_Master TM (NoLock) on TM.term_id = CSD.tendered_terminal_id
join it_cfg..Term_Grp_Master TGM (NoLock) on TGM.term_grp_id = TM.term_grp_id and TGM.ent_id = 1
join ig_dimension..Check_Type_Dimension CTD (NoLock) on CTD.check_type_dim_id = CSD.check_type_dim_id
where transaction_data_id in (select transaction_data_id
from ig_business..Check_Sales_Detail CSD (NoLock)
join it_cfg..Terminal_Master TM on TM.term_id = CSD.tendered_terminal_id
where tendered_date_time between GETDATE()-1 + '06:00:00:000' and GETDATE() + '05:59:59:997'
and TM.term_grp_id in (SELECT distinct term_grp_id from ig_mrvCustomisations.dbo.vw_TerminalsByProfitCentre WHERE store_name = #STORENAME))
and (CSD.associated_check_number = 0 and CSD.refund_flag = 0 and void_reason_dim_id = 0)
group by TGM.term_grp_name, CTD.check_type_name
) as one
Group By one.term_grp_name,
one.revenue_category_name,
one.check_type_name
ORDER BY [Date] asc, [Terminal Group Name] asc
Update: When I remove the Declare and set from the beginning of the query I get the following error:
You have declared and specified the #STREENAME variable in your code so SSRS has not need to set it, it will always be 'IVY'
Comment out the following two lines
DECLARE #STORENAME NVARCHAR(800)
SET #STORENAME = 'IVY'
It should not work.
NOTE: Parameter names are case sensistive so the query parameter name #STORENAME should match the SSRS parmatername EXACTLY excluding the # symbol.

Tuning Slow Performing Queries

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.

how to calculate from each row value in sql

I have a table named general_ledger from which I need to show dr_amount, cr_amount and the balance between them as running_balance. That's why I have written a query that is given below. But I am getting the result of each query like the balance only of current row. But I need to produce the result with the remaining balance. Suppose First row dr_balance is 20000 and cr_balance is 5000 and remaining balance is 15000. In second row only cr_balance is 5000. Now the result should be 10000 with the deduction but my result is -5000. I have no idea how to fix this. Can anyone please help me on this? I need your help very much. Here is my query given below :
SELECT '' AS cost_center_id
, '' AS cost_center_name
, '' AS office_code
, CONVERT('2013-02-01',DATETIME) AS transaction_date
, '' AS accounts_head_id
, '' AS account_name
, '' AS opposite_accounts_head_id
, '' AS opposite_account_name
, 'Opening Balance' AS particulars
, tempOpeningBalance.dr_amount
, tempOpeningBalance.cr_amount
, '' AS voucher_no
, '' AS vin
FROM (SELECT IFNULL(mcoa.account_code,'1101010101100321') AS account_code
, IFNULL(mcoa.account_name,'Cash') AS account_name
, IFNULL(mcoa.account_type,'ASSET') AS accountType
, CAST(IFNULL(SUM(IFNULL(maingl.dr_balance,0)),0) AS DECIMAL(27,5)) AS dr_amount
, CAST(IFNULL(SUM(IFNULL(maingl.cr_balance,0)),0) AS DECIMAL(27,5)) AS cr_amount
FROM master_chart_of_accounts AS mcoa
INNER JOIN chart_of_accounts AS coa ON (mcoa.id = coa.master_chart_of_accounts_id AND mcoa.id = 80)
LEFT JOIN general_ledger AS maingl ON (coa.id = maingl.accounts_head_id AND coa.account_code='1101010101100321')
INNER JOIN
( SELECT gl.accounts_head_id, MAX(gl.gl_id) AS max_gl_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
FROM general_ledger AS gl
-- INNER JOIN voucher_info AS vi ON (gl.voucher_info_id = vi.id)
-- WHERE vi.posting_date < '2013-02-01' AND
WHERE gl.transaction_date < '2013-02-01' AND
gl.cost_center_id IN ('BI0000000000000000000001') AND
gl.country_id IN (1) AND
gl.office_code IN ('UG500013') AND
1=1
GROUP BY gl.accounts_head_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
ORDER BY gl.accounts_head_id
) AS tmpgl
ON ( maingl.office_code = tmpgl.office_code
AND maingl.office_type = tmpgl.office_type
AND maingl.accounts_head_id = tmpgl.accounts_head_id
AND maingl.country_id = tmpgl.country_id
AND maingl.cost_center_id = tmpgl.cost_center_id
AND maingl.gl_id = tmpgl.max_gl_id
)
WHERE mcoa.account_status_id = 1 AND
coa.account_status_id = 1
) AS tempOpeningBalance
UNION
SELECT vi.cost_center_id
, cc.center_name AS cost_center_name
, gl.office_code
, vi.posting_date AS transaction_date
, vd.accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.accounts_head_id) AS account_name
, vd.opposite_accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.opposite_accounts_head_id) AS opposite_account_name
, vd.particulars
, gl.dr_amount AS dr_amount -- here to check
, gl.cr_amount AS cr_amount
, vi.voucher_no
, vi.vin
FROM general_ledger AS gl
INNER JOIN voucher_info AS vi
ON (gl.voucher_info_id = vi.id)
INNER JOIN cost_center AS cc
ON (vi.cost_center_id = cc.id)
INNER JOIN voucher_details AS vd
ON (vi.id = vd.voucher_info_id)
INNER JOIN chart_of_accounts AS coa
ON (vd.accounts_head_id = coa.id)
WHERE vi.posting_date BETWEEN '2013-02-01' AND'2013-02-28'
AND vi.voucher_status_id = 3
AND vd.status_id = 1
AND vi.office_code = 'UG500063'
AND coa.account_code='1101010101100321'
AND coa.cost_center_id = 'BI0000000000000000000001'
ORDER BY cost_center_name
, office_code
, transaction_date;
Use a variable like this
SET #running_balance=0;
SELECT dr_amount AS dr_amount
, cr_amount AS cr_amount
, #running_balance := (#running_balance + dr_amount - cr_amount)
FROM general_ledger

mysql get difference of two sum on the same table

how can i get the result in just one query instead of this one:
SELECT SUM(`quantity`) as type0 FROM `fruits_delivery`
WHERE `fid`='1001' AND `type`=0;
result_1 = type0 ;
SELECT SUM(`quantity`) as type1 FROM `fruits_delivery`
WHERE `fid`='1001' AND `type`=1;
result_2 = type1 ;
final_result = result_1 - result_2;
You should use this
SELECT sum(IF(`type`=0, `quantity`, 0))-sum(IF(`type`=1, `quantity`, 0))
AS `final_result`
FROM `fruits_delivery`
WHERE `fid` = '1001'
sqlfiddle
Old Answer
SELECT T1.result - T2.result AS `final_result`
FROM (SELECT Sum(`quantity`) AS result,
`fid`
FROM `fruits_delivery`
WHERE `fid` = '1001'
AND `type` = 0
LIMIT 1) AS T1
JOIN (SELECT Sum(`quantity`) AS result,
`fid`
FROM `fruits_delivery`
WHERE `fid` = '1001'
AND `type` = 1
LIMIT 1) AS T2
ON ( T1.fid = T2.fid )
SQLFiddle
Alternatively, you can also do it using CASE
SELECT SUM(CASE WHEN type = 0 THEN quantity ELSE 0 END) -
SUM(CASE WHEN type = 1 THEN quantity ELSE 0 END)
AS final_result
FROM fruits_delivery
WHERE fid = '1001'
SQLFiddle Demo