There is already an object named '##tempTable' in the database - sql-server

When executing the query below, I am receiving the error: There is already an object named '##tempTable' in the database. I am using a temporary table to insert the results and do other things not important to the question, but I need this if statement because there are a few minor differences in the queries and I don't know how to consolidate into 1 query. The error occurs in the else statement SELECT... INTO ##tempTable because I already perform this operation in the if. Is there any work around to this besides getting rid of the if else statement and consolidatin into one query?
IF #isQuintile = 1
BEGIN
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID, 0 AS 'fkDemographicCodeID', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_0', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) AS 'Count_0', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '0') AS 'BandID_0', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_1', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) AS 'Count_1', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '1') AS 'BandID_1'
INTO ##tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue)
OR ((CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore)
OR (CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore)))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
END
ELSE
BEGIN
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID, 0 AS 'fkDemographicCodeID', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_0', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) AS 'Count_0', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '0') AS 'BandID_0', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_1', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) AS 'Count_1', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '1') AS 'BandID_1'
INTO ##tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
END
EDIT Should have specified, but the reason I am selecting INTO is because the select is created dynamically so I don't know how many columns there will be. In my example I just showed what it would look like if there was only count, percent, and band 0 and 1 selected.

You need to Check Some thing like this Before Creating Temporary Tables
if OBJECT_ID(''tempdb..##tempTable) is not null
drop table ##tempTable
Then Your
SELECT * INTO ##tempTable......

##tempTable(Global temporary table) and #temptable(local Temporary table)
See the difference..
Local and global temporary tables in SQL Server
create table #tempTable(declare the columns here..)
IF #isQuintile = 1
BEGIN
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID, 0 AS 'fkDemographicCodeID', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_0', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) AS 'Count_0', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '0') AS 'BandID_0', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_1', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) AS 'Count_1', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '1') AS 'BandID_1'
INTO #tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue)
OR ((CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore)
OR (CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore)))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
END
ELSE
BEGIN
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID, 0 AS 'fkDemographicCodeID', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_0', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) AS 'Count_0', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '0') AS 'BandID_0', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_1', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) AS 'Count_1', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '1') AS 'BandID_1'
INTO #tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
END

You don't need to use SELECT INTO...
Just create the temp table (local or global) first and the do an INSERT INTO...SELECT:
IF (OBJECT_ID(N'tempdb..#tempTable') IS NOT NULL)
BEGIN
DROP TABLE #tempTable;
END;
CREATE TABLE #tempTable (
pkSchoolYearID datatype,
pkTestInstanceID datatype,
fkTest_SubjectID datatype,
fkDemographicCodeID INT
Percent_0 datatype
Count_0 datatype,
BandID_0 datatype,
Percent_1 datatype,
Count_1 datatype,
BandID_1 datatype
);
IF (#isQuintile = 1)
BEGIN
INSERT INTO #tempTable -- this has been added!!
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, ...
-- INTO ##tempTable -- this has been removed!!
INNER JOIN StudentTests
ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
...

Related

T-SQL, repeated same scalar subquery performance in views

Below is a simple query that retrieves Students and their exam results. The same student can take the same exam multiple times. The subqueries retrieve the latest exam results for each student. As you can see, the Line X (which retrieves the latest Exam ID) is exactly the same in every subquery for each row. How to store or cache the result of Line X to prevent three times execution for each row?
I cannot use stored procedure or functions for this task, it has to be a VIEW for additional filtering.
SELECT S.*,
(
SELECT COUNT(*) FROM ExamAnswers WHERE
IsCorrectAnswer IS NOT NULL AND
IsCorrectAnswer = 1 AND
ExamID =
(SELECT TOP(1) ID FROM Exams E WHERE E.StudentID = S.ID ORDER BY ID DESC) --Line X
) CorrectAnswerCount,
(
SELECT COUNT(*) FROM ExamAnswers EA WHERE
EA.IsCorrectAnswer IS NOT NULL AND
EA.IsCorrectAnswer = 0 AND
EA.ExamID =
(SELECT TOP(1) ID FROM Exams E WHERE E.StudentID = S.ID ORDER BY ID DESC) --Line X
) WrongAnswerCount,
(
SELECT COUNT(*) FROM ExamAnswers WHERE
IsCorrectAnswer IS NULL AND
ExamID =
(SELECT TOP(1) ID FROM Exams E WHERE E.StudentID = S.ID ORDER BY ID DESC) --Line X
) UnansweredQuestionCount
FROM Students S
You can do it like this
SELECT S.*,
CA.*
FROM Students S
CROSS APPLY (SELECT SUM(CASE WHEN IsCorrectAnswer = 1 THEN 1 ELSE 0 END) AS CorrectAnswerCount,
SUM(CASE WHEN IsCorrectAnswer = 0 THEN 1 ELSE 0 END) AS WrongAnswerCount,
SUM(CASE WHEN IsCorrectAnswer IS NULL THEN 1 ELSE 0 END) AS UnansweredQuestionCount
FROM ExamAnswers EA
WHERE EA.ExamID = (SELECT TOP(1) ID
FROM Exams E
WHERE E.StudentID = S.ID
ORDER BY ID DESC)) CA
What about this approach :
WITH
T AS
(
SELECT Student_id,
SUM(CASE IsCorrectAnswer WHEN 1 THEN 1 END) AS COUNT_TRUE,
SUM(CASE IsCorrectAnswer WHEN 0 THEN 1 END) AS COUNT_FALSE,
SUM(CASE WHEN IsCorrectAnswer IS NULL THEN 1 END) AS COUNT_UNKNOWN
FROM ExamAnswers AS EA
WHERE EA.ExamID = (SELECT MAX(ID)
FROM Exams E
WHERE E.StudentID = S.ID)
GROUP BY Student_id
)
SELECT S.*, COUNT_TRUE, COUNT_FALSE, COUNT_UNKNOWN
FROM Students AS S
JOIN T ON S.ID = T.Student_id

SQL: I need advice on how best to accomplish a complicated query

I'm working on a complicated query that I need to produce for a report. The query gives me what I need, but takes about 5 mins to run. For a report, this isn't acceptable, so I want to dump these results into a table via an overnight job and truncate the table before it runs each time. Where I'm running into trouble is how best to accomplish this, given how the query is structured, so I was hoping to get input on how I might do this. I'll break the query down as best I can into a mile-high view below:
CREATE TABLE #SALESDATA
(
...
)
INSERT INTO #SALESDATA
EXEC STAGING_DATA_PROC
WITH CTE1 AS
(
PRELIMINARY DATA 1
JOINED WITH #SALESDATA
),
CTE2 AS
(
PRELIMINARY DATA 2
JOINED WITH #SALESDATA
)
So what I first attempted to do is tried to circumvent the STAGING_DATA_PROC by just making it a query in its place, but it itself contains a few INSERTS into temp tables and doesn't seem to like the nesting of inserts in that order.
Any insight into how I might go about this?
UPDATE 1: This is the SQL that is taking about 5 mins to run. I have since replaced my SP feeding a temp table to a stand alone table that gives results instantly.
with basedata as (
select distinct a.order_num
,a.Period_Date
,a.year as std_the_year
,a.Month as std_the_month
,a.customer as std_StandardAcctNo
,b.salesperson
,isnull(ac.counter,0) [Appearance_Count]
,isnull(b.[Year],0) [The_Year]
,isnull(b.[Month],0) [The_Month]
,isnull(b.customer,0) [CustomerName]
,sum(isnull(b.Gallons,0)) [Gallon_Qty]
,sum(isnull(b.sales,0)) [Total_Sale]
,sum(isnull(b.gm,0)) [Total_Gross_Profit]
from (select distinct a.year
,a.month
,b.customer
,convert(integer,convert(varchar(4),a.Year) + right('00' + convert(varchar(2),a.month),2)) as order_num
,convert(date,convert(varchar(2),a.Month) + '/01/' + convert(varchar(4),a.Year)) as Period_Date
from IdealElephantSalesData a
join (select distinct customer from IdealElephantSalesData) b on 1 = 1
) a
join RicoCustom..Appearance_Count ac on a.customer = ac.customer_alias
left join IdealElephantSalesData b on a.customer = b.customer and a.Month = b.Month and a.Year = b.Year
group by a.order_num
,a.Period_Date
,a.year
,a.Month
,a.customer
,b.salesperson
,ac.counter
,b.[Year]
,b.[Month]
,b.customer
)
, saleslist as (
select distinct salesperson
,Appearance_Count
,Period_Date
,std_the_month
,std_the_year
,std_StandardAcctNo
,isnull(sum(Total_Gross_Profit),0) Period_GP
from basedata
group by salesperson, Appearance_Count, Period_Date, std_StandardAcctNo,std_the_month,std_the_year
), core_GP as (
select distinct a.customer
,convert(date,convert(varchar(2),a.month) + '/01/' + convert(varchar(4),a.year)) as Period_Date
,sum(a.gm) as Period_GP
from IdealElephantSalesData a
join RicoCustom..Appearance_Count ac on ac.customer_alias = a.customer
group by counter, convert(date,convert(varchar(2),a.month) + '/01/' + convert(varchar(4),a.year)), a.customer
), GroupedData AS (
SELECT distinct cgp.std_StandardAcctNo, cgp.Period_Date, sum(cgp.[Total_Gross_Profit]) as Period_GP, Appearance_Count
FROM basedata cgp
group by cgp.std_StandardAcctNo, cgp.Period_Date, Appearance_Count
), GP_Grouping as (
select std_StandardAcctNo
,min(Period_Date) as range_start
,max(Period_Date) as range_end
,count(*) as range_count
,GP_group
from (
select std_StandardAcctNo, Period_Date, case when Period_GP = 0 then 0 else 1 end as GP_Group
,row_number() over (PARTITION BY std_StandardAcctNo, case when Period_GP = 0 then 0 else 1 end order by Period_Date) as rn
,row_number() over (PARTITION BY std_StandardAcctNo, case when Period_GP = 0 then 0 else 1 end order by Period_Date) - row_number() over (PARTITION BY std_StandardAcctNo order by Period_Date) as grp
,row_number() over (PARTITION BY std_StandardAcctNo order by Period_Date) as grp2
from GroupedData
) a
group by std_StandardAcctNo, grp, GP_Group
),GP_Group2 as (
select gd.*, max(gpg_prev.range_end) as last_zero_group
FROM GroupedData gd
left join GP_Grouping gpg on gd.std_StandardAcctNo = gpg.std_StandardAcctNo and gd.Period_Date between gpg.range_start and gpg.range_end
left join (select * from GP_Grouping where GP_Group = 0 and range_count >= 12) gpg_prev on gpg_prev.std_StandardAcctNo = gd.std_StandardAcctNo and gpg.range_start > gpg_prev.range_end
group by gd.std_StandardAcctNo, Period_Date, Period_GP, Appearance_Count, gpg.range_count
), GP_Group3 as (
SELECT gd.*
,Appearance_Cnt_Rel = case when gd.last_zero_group is null then Appearance_Count else ROW_NUMBER() OVER(PARTITION BY gd.std_StandardAcctNo, gd.last_zero_group ORDER BY gd.Period_Date) end
FROM GP_Group2 gd
), almost_done as (
select distinct bd.order_num
,bd.Period_Date
,bd.std_the_year
,bd.std_the_month
,bd.std_StandardAcctNo
,case when bd.[Appearance_Count] > 0 then bd.[Appearance_Count]
when isnull(c.Appearance_Count,0) > 0 then c.Appearance_Count + 1
when isnull(d.Appearance_Count,0) > 0 then d.Appearance_Count + 2
when isnull(e.Appearance_Count,0) > 0 then e.Appearance_Count + 3
else 0
end as Appearance_Count
,bd.[The_Year]
,bd.[The_Month]
,bd.[CustomerName]
,bd.[Gallon_Qty]
,bd.[Total_Sale]
,isnull(c.Appearance_Count,0) as Prev_Count
,isnull(d.Appearance_Count,0) as month2_Count
,isnull(e.Appearance_Count,0) as month3_Count
,case when bd.salesperson is not null then bd.salesperson
when c.salesperson is not null then c.salesperson
when d.salesperson is not null then d.salesperson
when e.salesperson is not null then e.salesperson
else 'NA' end [SalesPerson]
,case when bd.[Appearance_Count] is null and c.[Appearance_Count] is null and d.[Appearance_Count] is null then e.Period_GP else 0 end [Lost_Gross_Profit]
,case when bd.Appearance_Count = 1 then bd.Total_Gross_Profit else 0 end as 'New_Cust_GP'
,case when bd.Appearance_Count <= 12 then bd.Total_Gross_Profit else 0 end as 'Young_Cust_GP'
,case when bd.Appearance_Count > 12 then bd.Total_Gross_Profit else 0 end as 'Old_Cust_GP'
,ROW_NUMBER() OVER (PARTITION BY bd.std_StandardAcctNo, bd.std_The_Year, bd.std_The_Month ORDER BY (bd.std_StandardAcctNo) DESC) as UNI_Period
,bd.Total_Gross_Profit as SalesP_GP
,isnull(cg.Period_gp,0) as Period_gp
,case when isnull(b_prev.Period_gp,0) > 0 then isnull(b_prev.Period_gp,0)
when isnull(d.Period_gp,0) > 0 then isnull(d.Period_gp,0)
when isnull(e.Period_gp,0) > 0 then isnull(e.Period_gp,0)
else 0 end as Prev_Period_GP
,h.Mat_MoM_Shift
,case when isnull(b_prev.Period_gp,0) > 0 then isnull(b_prev.Period_gp,0)
when isnull(d.Period_gp,0) > 0 then isnull(d.Period_gp,0)
when isnull(e.Period_gp,0) > 0 then isnull(e.Period_gp,0)
else 0 end * h.Mat_MoM_Shift as Expected_GP
,isnull(c.Period_gp,0) as True_Prev_GP
,isnull(d.Period_gp,0) as True_2month_GP
,isnull(e.Period_gp,0) as True_3month_GP
,ideal_candidate = case when ((isnull(c.Period_gp,0) + isnull(d.Period_gp,0) + isnull(bd.Total_Gross_Profit,0)) / 3 >= 800) and isnull(c.Period_gp,0) >= 150 and isnull(d.Period_gp,0) >= 150 and isnull(bd.Total_Gross_Profit,0) >= 150 then 'Y' else 'N' end
,eleph_candidate = case when ((isnull(c.Period_gp,0) + isnull(d.Period_gp,0) + isnull(bd.Total_Gross_Profit,0)) / 3 >= 5000) and isnull(c.Period_gp,0) >= 1000 and isnull(d.Period_gp,0) >= 1000 and isnull(bd.Total_Gross_Profit,0) >= 1000 then 'Y' else 'N' end
from basedata bd
left join core_GP b_prev on bd.std_StandardAcctNo = b_prev.customer and b_prev.Period_Date = dateadd(month,-1,bd.Period_Date)
left join saleslist c on c.std_StandardAcctNo = bd.std_StandardAcctNo and c.Period_Date = dateadd(month,-1,bd.Period_Date) and case when bd.salesperson is not null then bd.salesperson else c.salesperson end = c.salesperson
left join saleslist d on d.std_StandardAcctNo = bd.std_StandardAcctNo and d.Period_Date = dateadd(month,-2,bd.Period_Date) and case when bd.salesperson is not null then bd.salesperson when c.salesperson is not null then c.salesperson else d.salesperson end = d.salesperson
left join saleslist e on e.std_StandardAcctNo = bd.std_StandardAcctNo and e.Period_Date = dateadd(month,-3,bd.Period_Date) and case when bd.salesperson is not null then bd.salesperson when c.salesperson is not null then c.salesperson when d.salesperson is not null then d.salesperson else e.salesperson end = e.salesperson
left join RicoCustom.dbo.[Rico_Global_Monthly] h on h.month = bd.std_the_month
left join core_GP cg on bd.std_StandardAcctNo = cg.customer and cg.Period_Date = bd.Period_Date
),get_ideal as (
select distinct min(ad.Period_Date) as ideal_Period_Date
,ad.std_StandardAcctNo
,rc.last_zero_group
from almost_done ad
left join GP_Group3 rc on rc.Period_Date = ad.Period_Date and rc.std_StandardAcctNo = ad.std_StandardAcctNo and rc.Period_GP = ad.Period_gp
where ideal_candidate = 'Y' and (rc.Appearance_Cnt_Rel between 3 and 6)
group by ad.std_StandardAcctNo,rc.last_zero_group
), get_elephant as (
select distinct min(ad.Period_Date) as eleph_Period_Date
,ad.std_StandardAcctNo
,rc.last_zero_group
from almost_done ad
left join GP_Group3 rc on rc.Period_Date = ad.Period_Date and rc.std_StandardAcctNo = ad.std_StandardAcctNo and rc.Period_GP = ad.Period_gp
where eleph_candidate = 'Y' and (rc.Appearance_Cnt_Rel between 3 and 36)
group by ad.std_StandardAcctNo,rc.last_zero_group
)
select rc.Appearance_Cnt_Rel
,gi.ideal_Period_Date
,ge.eleph_Period_Date
,ad.*
from almost_done ad
left join GP_Group3 rc on rc.Period_Date = ad.Period_Date and rc.std_StandardAcctNo = ad.std_StandardAcctNo and rc.Period_GP = ad.Period_gp
left join get_ideal gi on ad.std_StandardAcctNo = gi.std_StandardAcctNo and ad.Period_Date = gi.ideal_Period_Date
left join get_elephant ge on ad.std_StandardAcctNo = ge.std_StandardAcctNo and ad.Period_Date = ge.eleph_Period_Date
where order_num > 201001
GO
Have you tried breaking your complicated query into smaller queries that load the data into temporary tables. You can use the temporary tables to build your final result. With the temporary tables, you can build the necessary indexes against them to ensure better performance. Additionally, you will be working with smaller subsets of the data which should result in better performance.

an expression of non-boolean type specified in a context where a condition is expected near 'type'

I am new to SSRS topics and I got this error while preparing the report plz help me to solve this. I have kept the query here kindly go through it.
SELECT T0.DocNum AS 'SO#', T6.DocNum as 'PO#', t1.LineTotal AS 'SO Amount', T6.DocEntry, T0.CardName, T6.U_enduserName, T11.QryGroup10 AS 'Major A/C Y/N',
T6.DocEntry AS Expr1, T6.CardCode, T6.CardName AS Expr2, T6.NumAtCard, T6.DocDate, t5.ItemCode, t5.Dscription, T7.U_itmdes, t5.Quantity, t5.LineTotal,
CASE WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal] * 2.5 ELSE T5.[LineTotal] END AS 'LineTotal with DTS amt', T10.ItmsGrpNam, T8.Location,
CASE WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal' ELSE 'Product' END AS 'Lic Type'
If((((T10.ItmsGrpNam="ADESK-AEC" and T10.ItmsGrpNam="ADESK-AEC-INFRA") and T1.Lic Type="Product" and T11.QryGroup10="No")),"AEC - ENI",If(((T10.ItmsGrpNam="ADESK-OPEN" and T10.ItmsGrpNam="ADESK-HORIZONTAL") and T1.Lic Type="Product" and T11.QryGroup10="No"),"PSEB",If(((T10.ItmsGrpNam="ADESK-M&E" or T10.ItmsGrpNam="ADESK-MFG") and T1.Lic Type="Product" and T11.QryGroup10="No"),T10.ItmsGrpNam,If(((T10.ItmsGrpNam="ADESK-AEC" and T10.ItmsGrpNam="ADESK-AEC-INFRA") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"AEC & ENI - Sub Renewal",If(((T10.ItmsGrpNam="ADESK-OPEN" and T10.ItmsGrpNam="ADESK-HORIZONTAL") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"PSEB - Sub Renewal",If(((T10.ItmsGrpNam="ADESK-M&E" or T10.ItmsGrpNam="ADESK-MFG") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"MFG - Sub Renewal","MFG - Sub Renewal"))))))
FROM OCRD AS T11 INNER JOIN
ORDR AS T0 ON T11.CardCode = T0.CardCode INNER JOIN
RDR1 AS t1 ON T0.DocEntry = t1.DocEntry LEFT OUTER JOIN
POR1 AS t3 ON t3.BaseEntry = t1.DocEntry AND t3.BaseLine = t1.LineNum AND t3.ItemCode = t1.ItemCode LEFT OUTER JOIN
PDN1 AS t4 ON t4.BaseEntry = t3.DocEntry AND t4.BaseLine = t3.LineNum AND t4.ItemCode = t3.ItemCode INNER JOIN
PCH1 AS t5 ON t5.BaseEntry = t4.DocEntry AND t5.ItemCode = t4.ItemCode AND t5.BaseLine = t4.LineNum AND t5.TargetType <> 19 INNER JOIN
OPCH AS T6 ON t5.DocEntry = T6.DocEntry INNER JOIN
OITM AS T7 ON t5.ItemCode = T7.ItemCode INNER JOIN
OLCT AS T8 ON t5.LocCode = T8.Code CROSS JOIN
OITG AS T10
WHERE (T10.ItmsTypCod = (CASE WHEN T7.[QryGroup1] = 'y' THEN 1 WHEN T7.[QryGroup2] = 'y' THEN 2 WHEN T7.[QryGroup3] = 'y' THEN 3 WHEN T7.[QryGroup4] = 'y' THEN
4 WHEN T7.[QryGroup5] = 'y' THEN 5 WHEN T7.[QryGroup6] = 'y' THEN 6 WHEN T7.[QryGroup7] = 'y' THEN 7 WHEN T7.[QryGroup8] = 'y' THEN 8 WHEN T7.[QryGroup9]
= 'y' THEN 9 WHEN T7.[QryGroup60] = 'y' THEN 60 ELSE 0 END)) AND (T6.CardCode <> 'VDD1-100233')
and T6.[DocDate] >=(#date1) and T6.[DocDate] <=(#date2)
Try to do something like this first,
DECLARE #date1 AS DATETIME = '' --your date1
DECLARE #date2 AS DATETIME = '' --your date2
SELECT *
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode=T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry=t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry =t1.DocEntry AND t3.BaseLine=t1.LineNum
AND t3.ItemCode=t1.ItemCode LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry=t3.DocEntry
AND t4.BaseLine=t3.LineNum
AND t4.ItemCode=t3.ItemCode INNER JOIN PCH1 AS t5 ON t5.BaseEntry=t4.DocEntry
AND t5.ItemCode=t4.ItemCode
AND t5.BaseLine=t4.LineNum
AND t5.TargetType<>19 INNER JOIN OPCH AS T6 ON t5.DocEntry=T6.DocEntry INNER
JOIN OITM AS T7 ON t5.ItemCode=T7.ItemCode INNER JOIN OLCT AS T8 ON t5.LocCode
=T8.Code CROSS JOIN OITG AS T10 WHERE (
T10.ItmsTypCod=(
CASE
WHEN T7.[QryGroup1]='y' THEN 1
WHEN T7.[QryGroup2]='y' THEN 2
WHEN T7.[QryGroup3]='y' THEN 3
WHEN T7.[QryGroup4]='y' THEN 4
WHEN T7.[QryGroup5]='y' THEN 5
WHEN T7.[QryGroup6]='y' THEN 6
WHEN T7.[QryGroup7]='y' THEN 7
WHEN T7.[QryGroup8]='y' THEN 8
WHEN T7.[QryGroup9]='y' THEN 9
WHEN T7.[QryGroup60]='y' THEN 60
ELSE 0
END
)
)
AND (T6.[CardCode] <> 'VDD1-100233')
AND T6.[DocDate] >= (#date1)
AND T6.[DocDate] <= (#date2)
If it gives you result then try to add below variables one by one,
T0.DocNum AS 'SO#'
,T6.DocNum AS 'PO#'
,t1.LineTotal AS 'SO Amount'
,T6.DocEntry
,T0.CardName
,T6.U_enduserName
,T11.QryGroup10 AS 'Major A/C Y/N'
,T6.DocEntry AS Expr1
,T6.CardCode
,T6.CardName AS Expr2
,T6.NumAtCard
,T6.DocDate
,t5.ItemCode
,t5.Dscription
,T7.U_itmdes
,t5.Quantity
,t5.LineTotal
,CASE
WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal]*2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt'
,T10.ItmsGrpNam
,T8.Location
,CASE
WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type'
IF (
(
(
(
T10.ItmsGrpNam="ADESK-AEC"
AND T10.ItmsGrpNam="ADESK-AEC-INFRA"
)
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
)
,[AEC - ENI]
,IF(
(
(
T10.ItmsGrpNam="ADESK-OPEN"
AND T10.ItmsGrpNam="ADESK-HORIZONTAL"
)
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
,"PSEB"
,IF(
(
(T10.ItmsGrpNam="ADESK-M&E" OR T10.ItmsGrpNam="ADESK-MFG")
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
,T10.ItmsGrpNam
,IF(
(
(
T10.ItmsGrpNam="ADESK-AEC"
AND T10.ItmsGrpNam="ADESK-AEC-INFRA"
)
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"AEC & ENI - Sub Renewal"
,IF(
(
(
T10.ItmsGrpNam="ADESK-OPEN"
AND T10.ItmsGrpNam="ADESK-HORIZONTAL"
)
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"PSEB - Sub Renewal"
,IF(
(
(T10.ItmsGrpNam="ADESK-M&E" OR T10.ItmsGrpNam="ADESK-MFG")
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"MFG - Sub Renewal"
,"MFG - Sub Renewal"
)
)
)
)
)
)
Note: It will throw error:
Incorrect syntax near ','.
Make it as per your requirement. If is alias then make sure it should work as single variable.
Also I noted you are fetching different variables but you have not put , after AS 'Lic Type'. Check this also.
Below query using CASE ,
DECLARE #date1 AS DATETIME
DECLARE #date2 AS DATETIME
SELECT T0.DocNum AS 'SO#'
,T6.DocNum AS 'PO#'
,t1.LineTotal AS 'SO Amount'
,T6.DocEntry
,T0.CardName
,T6.U_enduserName
,T11.QryGroup10 AS 'Major A/C Y/N'
,T6.DocEntry AS Expr1
,T6.CardCode
,T6.CardName AS Expr2
,T6.NumAtCard
,T6.DocDate
,t5.ItemCode
,t5.Dscription
,T7.U_itmdes
,t5.Quantity
,t5.LineTotal
,CASE
WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal]*2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt'
,T10.ItmsGrpNam
,T8.Location
,CASE
WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type'
,
CASE
WHEN T10.ItmsGrpNam='ADESK-AEC' AND T10.ItmsGrpNam='ADESK-AEC-INFRA' AND T1.[Lic TYPE]='Product' AND T11.QryGroup10='No"' THEN 'AEC - ENI'
WHEN T10.ItmsGrpNam='ADESK-OPEN' AND T10.ItmsGrpNam='ADESK-HORIZONTAL' AND
T1.[Lic TYPE]='Product' AND T11.QryGroup10='No' THEN 'PSEB'
WHEN (T10.ItmsGrpNam='ADESK-M&E' OR T10.ItmsGrpNam='ADESK-MFG') AND T1.[Lic
TYPE]='Product' AND T11.QryGroup10='No' THEN T10.ItmsGrpNam
WHEN T10.ItmsGrpNam='ADESK-AEC' AND T10.ItmsGrpNam='ADESK-AEC-INFRA' AND T1.[Lic
TYPE]='Renewal' AND T11.QryGroup10='No' THEN '"AEC & ENI - Sub Renewal'
WHEN T10.ItmsGrpNam='ADESK-OPE' AND T10.ItmsGrpNam='ADESK-HORIZONTAL' AND
T1.[Lic TYPE]='Renewal' AND T11.QryGroup10='No' THEN
'PSEB - Sub Renewal'
WHEN (T10.ItmsGrpNam='ADESK-M&E' OR T10.ItmsGrpNam='ADESK-MFG') AND [T1.Lic
TYPE]='Renewal' AND T11.QryGroup10='No' THEN 'MFG - Sub Renewal'
ELSE 'MFG - Sub Renewal'
END
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode=T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry=t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry =t1.DocEntry AND t3.BaseLine=t1.LineNum
AND t3.ItemCode=t1.ItemCode LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry=t3.DocEntry
AND t4.BaseLine=t3.LineNum
AND t4.ItemCode=t3.ItemCode INNER JOIN PCH1 AS t5 ON t5.BaseEntry=t4.DocEntry
AND t5.ItemCode=t4.ItemCode
AND t5.BaseLine=t4.LineNum
AND t5.TargetType<>19 INNER JOIN OPCH AS T6 ON t5.DocEntry=T6.DocEntry INNER
JOIN OITM AS T7 ON t5.ItemCode=T7.ItemCode INNER JOIN OLCT AS T8 ON t5.LocCode
=T8.Code CROSS JOIN OITG AS T10 WHERE (
T10.ItmsTypCod=(
CASE
WHEN T7.[QryGroup1]='y' THEN 1
WHEN T7.[QryGroup2]='y' THEN 2
WHEN T7.[QryGroup3]='y' THEN 3
WHEN T7.[QryGroup4]='y' THEN 4
WHEN T7.[QryGroup5]='y' THEN 5
WHEN T7.[QryGroup6]='y' THEN 6
WHEN T7.[QryGroup7]='y' THEN 7
WHEN T7.[QryGroup8]='y' THEN 8
WHEN T7.[QryGroup9]='y' THEN 9
WHEN T7.[QryGroup60]='y' THEN 60
ELSE 0
END
)
)
AND (T6.[CardCode] <> 'VDD1-100233')
AND T6.[DocDate] >= (#date1)
AND T6.[DocDate] <= (#date2)
You have the following in several places in select part:
T1.Lic Type="Product"
You have to delimit that column. Change to this:
T1.[Lic Type]="Product"
It is a pain to gebug so many IIF operators. Change to CASE expressions. You will gain both in readability and standardization of your code. Also change double quotes to single quotes.
case when T10.ItmsGrpNam='ADESK-AEC' and T10.ItmsGrpNam='ADESK-AEC-INFRA' and T1.[Lic Type]='Product' and T11.QryGroup10='No"' then 'AEC - ENI'
when T10.ItmsGrpNam='ADESK-OPEN' and T10.ItmsGrpNam='ADESK-HORIZONTAL' and T1.[Lic Type]='Product' and T11.QryGroup10='No' then 'PSEB'
when (T10.ItmsGrpNam='ADESK-M&E' or T10.ItmsGrpNam='ADESK-MFG') and T1.[Lic Type]='Product' and T11.QryGroup10='No' then T10.ItmsGrpNam
when T10.ItmsGrpNam='ADESK-AEC' and T10.ItmsGrpNam='ADESK-AEC-INFRA' and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then'"AEC & ENI - Sub Renewal'
when T10.ItmsGrpNam='ADESK-OPE' and T10.ItmsGrpNam='ADESK-HORIZONTAL' and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then 'PSEB - Sub Renewal'
when (T10.ItmsGrpNam='ADESK-M&E' or T10.ItmsGrpNam='ADESK-MFG') and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then 'MFG - Sub Renewal'
else 'MFG - Sub Renewal' end
EDIT:
Here is the full statement:
DECLARE #date1 DATETIME, #date2 DATETIME
SELECT T0.DocNum AS 'SO#' ,
T6.DocNum AS 'PO#' ,
t1.LineTotal AS 'SO Amount' ,
T6.DocEntry ,
T0.CardName ,
T6.U_enduserName ,
T11.QryGroup10 AS 'Major A/C Y/N' ,
T6.DocEntry AS Expr1 ,
T6.CardCode ,
T6.CardName AS Expr2 ,
T6.NumAtCard ,
T6.DocDate ,
t5.ItemCode ,
t5.Dscription ,
T7.U_itmdes ,
t5.Quantity ,
t5.LineTotal ,
CASE WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal] * 2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt' ,
T10.ItmsGrpNam ,
T8.Location ,
CASE WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type' ,
CASE WHEN T10.ItmsGrpNam = 'ADESK-AEC'
AND T10.ItmsGrpNam = 'ADESK-AEC-INFRA'
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No"' THEN 'AEC - ENI'
WHEN T10.ItmsGrpNam = 'ADESK-OPEN'
AND T10.ItmsGrpNam = 'ADESK-HORIZONTAL'
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No' THEN 'PSEB'
WHEN ( T10.ItmsGrpNam = 'ADESK-M&E'
OR T10.ItmsGrpNam = 'ADESK-MFG'
)
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No' THEN T10.ItmsGrpNam
WHEN T10.ItmsGrpNam = 'ADESK-AEC'
AND T10.ItmsGrpNam = 'ADESK-AEC-INFRA'
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN '"AEC & ENI - Sub Renewal'
WHEN T10.ItmsGrpNam = 'ADESK-OPE'
AND T10.ItmsGrpNam = 'ADESK-HORIZONTAL'
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN 'PSEB - Sub Renewal'
WHEN ( T10.ItmsGrpNam = 'ADESK-M&E'
OR T10.ItmsGrpNam = 'ADESK-MFG'
)
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN 'MFG - Sub Renewal'
ELSE 'MFG - Sub Renewal'
END
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode = T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry = t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry = t1.DocEntry
AND t3.BaseLine = t1.LineNum
AND t3.ItemCode = t1.ItemCode
LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry = t3.DocEntry
AND t4.BaseLine = t3.LineNum
AND t4.ItemCode = t3.ItemCode
INNER JOIN PCH1 AS t5 ON t5.BaseEntry = t4.DocEntry
AND t5.ItemCode = t4.ItemCode
AND t5.BaseLine = t4.LineNum
AND t5.TargetType <> 19
INNER JOIN OPCH AS T6 ON t5.DocEntry = T6.DocEntry
INNER JOIN OITM AS T7 ON t5.ItemCode = T7.ItemCode
INNER JOIN OLCT AS T8 ON t5.LocCode = T8.Code
CROSS JOIN OITG AS T10
WHERE ( T10.ItmsTypCod = ( CASE WHEN T7.[QryGroup1] = 'y' THEN 1
WHEN T7.[QryGroup2] = 'y' THEN 2
WHEN T7.[QryGroup3] = 'y' THEN 3
WHEN T7.[QryGroup4] = 'y' THEN 4
WHEN T7.[QryGroup5] = 'y' THEN 5
WHEN T7.[QryGroup6] = 'y' THEN 6
WHEN T7.[QryGroup7] = 'y' THEN 7
WHEN T7.[QryGroup8] = 'y' THEN 8
WHEN T7.[QryGroup9] = 'y' THEN 9
WHEN T7.[QryGroup60] = 'y' THEN 60
ELSE 0
END ) )
AND ( T6.CardCode <> 'VDD1-100233' )
AND T6.[DocDate] >= ( #date1 )
AND T6.[DocDate] <= ( #date2 )

Convert from stored procedure to SQL Query

I want a SQL query for the third procedure
Convert this stored procedure to a SQL query :
CREATE PROC [WaterlilyT].[uisp_Rep_HRClearance_RND]
(
#pnCompCode DECIMAL(18,0)=0,
#pnClearanceNo VARCHAR(5000)='',
#AsonDate varchar(20)='1900-01-01'
)
AS
BEGIN
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb..#TempHRCLNos') IS NOT NULL
DROP TABLE #TempHRCLNos
SELECT CAST(val AS Decimal(18,0)) clslno
INTO #TempHRCLNos
FROM dbo.split(#pnClearanceNo,',')
CREATE NONCLUSTERED INDEX ix_TempHRCLslno ON #TempHRCLNos(clslno)
DECLARE #pnVisaReq decimal
SET #pnVisaReq = 0
DECLARE #ldAsonDate Date
SET #ldAsonDate = CONVERT(DATETIME, AsonDate, 103)
--if OBJECT_ID('tempdb..#TempHRCLVisaReq') is not null drop table #TempHRCLVisaReq
if OBJECT_ID('tempdb..#TempHRCLJoining') is not null drop table #TempHRCLJoining
SELECT c.serialno,d.posiref posname,d.gender,count(a.serialno) visareq,count(b.serialno) visarefused,count(e.serialno) visarec
Into #TempHRCLVisaReq
FROM [WaterlilyT].[vtwfhclearance] c
Join [WaterlilyT].[vtwfhvisaprocreq] a on a.clearno = c.serialno
join waterlilyt.vtwfhofferletter ofr on ofr.serialno = a.offrefno
join waterlilyt.vtwfhresbnk res on res.serialno = ofr.candcode
join [WaterlilyT].[vtwfdpclearance] d on d.serialno = c.serialno and d.gender = res.gender
left join [WaterlilyT].[vtwfhvisaprociss] b on b.visareq = a.serialno and b.visastat = 20
left join [WaterlilyT].[vtwfhvisaprociss] e on e.visareq = a.serialno and e.visastat = 10
where isnull(a.appstat,0) = 50
and (#pnCompCode =0 or (#pnCompCode !=0 and #pnCompCode = a.bcd))
and (#pnClearanceNo ='' or (#pnClearanceNo != '' and exists (select 1 from #TempHRCLNos where clslno=a.clearno)))
and (#ldAsonDate = '1900-01-01' or (#ldAsonDate <> '1900-01-01' and c.clearpdt < Dateadd(day,1,#ldAsonDate) ) )
Group by c.serialno,d.posiref,d.gender
SELECT c.serialno,e.codeval desg,f.gender gendercode ,count(jp.serialno) joincnt
Into #TempHRCLJoining
FROM WaterlilyT.vtwfhjoinprocess jp
join waterlilyt.vtwfhresbnk f on f.serialno = jp.candcd
Join [WaterlilyT].[vtwfhvisaprocreq] vreq on jp.offerno = isnull(vreq.offrefno,0)
Join [WaterlilyT].[vtwfhclearance] c on vreq.clearno = c.serialno
--Join UlexM.vmunmglobal e on isnull(e.serialno,'') = vreq.posname and gtype = 'DESIG' and isactive = 1 and islstlvl = 1
--Join [WaterlilyT].[vtwfdpclearance] d on d.serialno = c.serialno and d.posiref = isnull(e.strvalue,0) and d.gender = f.gender
join Ulexm.vmundgeneral e on e.mastcd = 'CLRPOS' and e.codeval = vreq.posname
Join [WaterlilyT].[vtwfdpclearance] d on d.serialno = c.serialno and d.posiref = isnull(e.codeval,0) and d.gender = f.gender
where isnull(jp.appstat,0) =50 and jp.jointyp <> 10 and isnull(vreq.appstat,0) = 50
and (#pnCompCode =0 or (#pnCompCode !=0 and #pnCompCode = jp.bcd))
and (#pnClearanceNo ='' or (#pnClearanceNo != '' and exists (select 1 from #TempHRCLNos where clslno=vreq.clearno)))
and (#ldAsonDate = '1900-01-01' or (#ldAsonDate <> '1900-01-01' and c.clearpdt < Dateadd(day,1,#ldAsonDate)) )
Group by c.serialno,e.codeval,f.gender
/*SELECT hc.serialno,SlNo,ClearanceNo,Convert(Varchar(10),Clearancedate,103) Clearancedate,Positioncode,PositionName,
hc.Gender,isnull(TotalNumber,0) TotalNumber,validityDate,
Case When validityDate >= Case when #ldAsonDate ='1900-01-01' then getdate() else #ldAsonDate end then
DATEDIFF(DAY,Case when #ldAsonDate ='1900-01-01' then getdate() else #ldAsonDate end,validityDate) Else 0 End DaysToGo,
--isnull(vreq.visareq,0) [VisaRequested],
isnull(req.visareq,0) [VisaRequested],
isnull(req.visarefused,0) RefusedByROP ,isnull(req.visareq,0)-isnull(req.visarefused,0) [VisaRecd],isnull(jp.joincnt,0) Joined,
(isnull(req.visareq,0)-isnull(req.visarefused,0)) - isnull(jp.joincnt,0) EmpYetToJoin,VisaExpired,
isnull(TotalNumber,0) - (isnull(req.visareq,0) + isnull(req.visarefused,0) + VisaExpired ) Pending
FROM WaterlilyT.vinforClearance hc
--left Join #TempHRCLVisaReq vreq on hc.serialno =vreq.serialno and hc.desg = vreq.desg
--Left Join #TempHRCLJoining jp on hc.serialno =jp.serialno and hc.desg =jp.desg
Left Join #TempHRCLJoining jp on hc.serialno =jp.serialno and hc.PositionCode =jp.desg and jp.gendercode = hc.gendercode
Left Join #TempHRCLVisaReq req on req.serialno = hc.serialno and req.posname = hc.PositionCode and req.gender = hc.gendercode
where (#pnCompCode =0 or (#pnCompCode !=0 and #pnCompCode = hc.bcd))
and (#pnClearanceNo ='' or (#pnClearanceNo != '' and exists (select 1 from #TempHRCLNos where clslno=hc.serialno)))
and (#ldAsonDate = '1900-01-01' or (#ldAsonDate <> '1900-01-01' and Clearancedate < Dateadd(day,1,#ldAsonDate) ) )*/
SELECT hc.serialno,SlNo,ClearanceNo,Convert(Varchar(10),Clearancedate,103) Clearancedate,Positioncode,PositionName,
hc.Gender,isnull(TotalNumber,0) TotalNumber,validityDate,
Case When validityDate >= Case when #ldAsonDate ='1900-01-01' then getdate() else #ldAsonDate end then
DATEDIFF(DAY,Case when #ldAsonDate ='1900-01-01' then getdate() else #ldAsonDate end,validityDate) Else 0 End DaysToGo,
isnull(req.visareq,0) [VisaRequested],
isnull(req.visarefused,0) RefusedByROP ,isnull(req.visarec,0) [VisaRecd],isnull(jp.joincnt,0) Joined,
isnull(req.visarec,0) - isnull(jp.joincnt,0) EmpYetToJoin,VisaExpired,
isnull(TotalNumber,0) - (isnull(req.visareq,0) + isnull(req.visarefused,0) + VisaExpired ) Pending
FROM WaterlilyT.vinforClearance hc
--left Join #TempHRCLVisaReq vreq on hc.serialno =vreq.serialno and hc.desg = vreq.desg
--Left Join #TempHRCLJoining jp on hc.serialno =jp.serialno and hc.desg =jp.desg
Left Join #TempHRCLJoining jp on hc.serialno =jp.serialno and hc.PositionCode =jp.desg and jp.gendercode = hc.gendercode
Left Join #TempHRCLVisaReq req on req.serialno = hc.serialno and req.posname = hc.PositionCode and req.gender = hc.gendercode
where (#pnCompCode =0 or (#pnCompCode !=0 and #pnCompCode = hc.bcd))
and (#pnClearanceNo ='' or (#pnClearanceNo != '' and exists (select 1 from #TempHRCLNos where clslno=hc.serialno)))
and (#ldAsonDate = '1900-01-01' or (#ldAsonDate <> '1900-01-01' and Clearancedate < Dateadd(day,1,#ldAsonDate) ) )
END

SQL WHERE clause issues

The problem I am having seems to come from my where clause and hardcoding.
I have two tables one with ID's and another with ID's and Scores for the ID's.
So my code looks a little something like this:
SELECT AVG(CAST(c.Score AS DEC(10,2))) AS avgTestC,
AVG(CAST(d.Score AS DEC(10,2))) AS avgTestD,
AVG(CAST(e.Score AS DEC(10,2))) AS avgTestE,
AVG(CAST(f.Score AS DEC(10,2))) AS avgTestF,
COUNT(DISTINCT c.ID) AS CountC,
COUNT(DISTINCT d.ID) AS CountD,
COUNT(DISTINCT e.ID) AS CountE,
COUNT(DISTINCT f.ID) AS CountF
FROM tblWithIds a,
JOIN tblScores b ON a.ID = b.ID AND b.Year = #Year
LEFT JOIN tblScores c ON a.ID = c.ID AND c.Year = #Year
LEFT JOIN tblScores d ON a.ID = d.ID AND d.Year = #Year
LEFT JOIN tblScores e ON a.ID = e.ID AND e.Year = #Year
LEFT JOIN tblScores f ON a.ID = f.ID AND f.Year = #Year
WHERE c.TestC = 'Test C'
d.TestD = 'Test D'
e.TestE = 'Test E'
f.TestF = 'Test F'
Now the problem is that when I add more to the where clause and almost identical "Tests" the where clause, it gives me NULL values for everything and 0's for the COUNT. The code above works properly but the test am I using have very similar names and the table was made poorly so all of the "Tests" names' are all in one column. I cannot debug as I am stuck using MSSQL 05 for now. Please help!
EDIT: After getting using the aggregate function SUM below from EricZ, if anyone else is interested I have found that
AVG( CASE WHEN b.Test = 'Test D' THEN CAST(b.Score AS DEC(10,2)) ELSE NULL END) AS avgTestC
to be the correct form for the AVG aggregate function.
You can use CASE to do COUNT, and just need JOIN table once
SELECT
AVG(CAST((CASE WHEN b.TestC = 'Test C' THEN b.Score ELSE 0 END) AS DEC(10,2))) AS avgTestC,
AVG(CAST((CASE WHEN b.TestD = 'Test D' THEN b.Score ELSE 0 END) AS DEC(10,2))) AS avgTestD,
AVG(CAST((CASE WHEN b.TestE = 'Test E' THEN b.Score ELSE 0 END) AS DEC(10,2))) AS avgTestE,
AVG(CAST((CASE WHEN b.TestF = 'Test F' THEN b.Score ELSE 0 END) AS DEC(10,2))) AS avgTestF,
SUM(CASE WHEN b.TestC = 'Test C' THEN 1 ELSE 0 END) AS CountC,
SUM(CASE WHEN b.TestD = 'Test D' THEN 1 ELSE 0 END) AS CountD,
SUM(CASE WHEN b.TestE = 'Test E' THEN 1 ELSE 0 END) AS CountE,
SUM(CASE WHEN b.TestF = 'Test F' THEN 1 ELSE 0 END) AS CountF
FROM tblWithIds a,
JOIN tblScores b ON a.ID = b.ID AND b.Year = #Year
Use CASE instead
SELECT SUM(CASE WHEN Something > 0 THEN Something ELSE 0 END) AS A, SUM(CASE WHEN Something2 > 0 THEN Something2 ELSE 0 END) AS B

Resources