SQL WHERE clause issues - sql-server

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

Related

Assigning multiple variables in one select

I have the following query:
SELECT
ROW_NUMBER() OVER(ORDER BY A.Price) AS R,
A.Price
FROM
TableA A
INNER JOIN
TableB B ON A.ID = B.ID
INNER JOIN
TableC C ON C.Code = A.Code
WHERE
C.Type = 125
AND A.Desc = 10000038
AND C.YearID = 10000021
GROUP BY
A.Price
This query returns
R
Price
1
165
2
487
3
1807
Is it possible assigning variables #a = 165, #b = 487, and #c = 1807 in one select?
I wrote this query:
WITH P AS (
SELECT
ROW_NUMBER() OVER(ORDER BY A.Price) AS R,
A.Price
FROM
TableA A
INNER JOIN
TableB B ON A.ID = B.ID
INNER JOIN
TableC C ON C.Code = A.Code
WHERE
C.Type = 125
AND A.Desc = 10000038
AND C.YearID = 10000021
GROUP BY
A.Price
)
SELECT
#a = (CASE WHEN [R] = 1 THEN P.[Price] END),
#b = (CASE WHEN [R] = 2 THEN P.[Price] END),
#c = (CASE WHEN [R] = 3 THEN P.[Price] END)
FROM P;
But only #c gets the value.
You need to aggregate. Your query, as it stands, returns 3 rows, which means that the variables are assigned values 3 times as well. What order this is in is arbitrary too, but it might be that #a is first assigned the value 165, then NULL, and then NULL again.
If you aggregate, you can return one row and then the assignments will work as you expect; with each variable being assigned 1 value (not 3):
SELECT #a = MAX(CASE WHEN [R] = 1 THEN P.[Price] END),
#b = MAX(CASE WHEN [R] = 2 THEN P.[Price] END),
#c = MAX(CASE WHEN [R] = 3 THEN P.[Price] END)
FROM P;

add a column to the select query which could be null

I would like to add another column to my select query called description inside posts table,
the problem is that this value could be null.
to make it clear, I have already linked foreign keys from tables Users, PostType and Votes.
Attaching the query:
SELECT po.id,
po.title,
CONVERT(varchar, po.pDate, 104) AS pDate,
pt.type,
us.userName,
SUM(CASE WHEN vt.isLike = 1 THEN 1 ELSE 0 END) AS upvotes,
SUM(CASE WHEN vt.isLike = 0 THEN 1 ELSE 0 END) AS downvotes
FROM Posts po
INNER JOIN PostType pt ON po.typeId = pt.id
INNER JOIN Users us ON po.userId = us.id
LEFT OUTER JOIN Votes vt ON vt.postId = po.id
GROUP BY po.id,
po.pDate,
po.title,
pt.type,
us.userName;
How to avoid group by null?
You can make that column non-nullable on the fly. So in the SELECT clause just add one more column to display CASE WHEN po.description IS NULL THEN 'present' ELSE 'absent' END AS description and repeat it in the GROUP BY clause CASE WHEN po.description IS NULL THEN 'present' ELSE 'absent' END
SELECT po.id,
po.title,
CASE WHEN po.description IS NULL THEN 'present' ELSE 'absent' END AS description,
CONVERT(varchar, po.pDate, 104) AS pDate,
pt.type,
us.userName,
SUM(CASE WHEN vt.isLike = 1 THEN 1 ELSE 0 END) AS upvotes,
SUM(CASE WHEN vt.isLike = 0 THEN 1 ELSE 0 END) AS downvotes
FROM Posts po
INNER JOIN PostType pt ON po.typeId = pt.id
INNER JOIN Users us ON po.userId = us.id
LEFT OUTER JOIN Votes vt ON vt.postId = po.id
GROUP BY po.id,
po.pDate,
po.title,
CASE WHEN po.description IS NULL THEN 'present' ELSE 'absent' END,
pt.type,
us.userName;

Add a WHERE clause in a complex SQL query

I want to pass a ShowRoomId value to the query below. The Employees table has a ShowRoomId column.
How can I do it?
My SQL query is as following:
SELECT *
FROM Employees A
OUTER APPLY (SELECT TOP 1 *
FROM EmployeeBasics B
WHERE (A.EmployeeID = B.EmployeeID)
ORDER BY B.BasicUpdateDate DESC) AS B
OUTER APPLY (
SELECT C.EmployeeId , count(*) AS TotalAbsent
FROM EmployeeAbsents C
WHERE C.AbsentDate BETWEEN '2016-05-01' AND '2016-05-30' AND A.EmployeeID = C.EmployeeID
GROUP BY C.EmployeeId
) AS C
OUTER APPLY (
SELECT EmployeeId,
SUM(CASE WHEN TransctionTypeId = 1 THEN Amount ELSE 0 END) AS Payment,
SUM(CASE WHEN TransctionTypeId = 2 THEN Amount ELSE 0 END) AS RecoverSalary,
SUM(CASE WHEN TransctionTypeId = 3 THEN Amount ELSE 0 END) AS RecoverCash
FROM dbo.EmployeeAdvances D
WHERE A.EmployeeID = D.EmployeeID
GROUP BY EmployeeId
) AS D
Simply use a WHERE clause at the end as following:
... YOUR SELECT ...
WHERE Col = ...YourCondition...
OR
Use WITH keyword to keep your current SELECT-statement in a cte. Then do your query on it.
WITH cte AS
(
... YOUR SELECT ...
)
SELECT *
FROM cte
WHERE Col = ...YourCondition...
OR
You can add your SELECT-statement in to parentheses and name it with an allias name. So you can do query on it too.
SELECT *
FROM
(
... YOUR SELECT ...
) t
WHERE t.Col = ...YourCondition...
As per Giorgi Nakeuri's advice, I added the WHERE clause at the end of the statement.
And it works for me. Revised code is here:
SELECT *
FROM Employees A
OUTER APPLY (SELECT TOP 1 *
FROM EmployeeBasics B
WHERE (A.EmployeeID = B.EmployeeID)
ORDER BY B.BasicUpdateDate DESC) AS B
OUTER APPLY (
SELECT C.EmployeeId , count(*) AS TotalAbsent
FROM EmployeeAbsents C
WHERE C.AbsentDate BETWEEN '2016-05-01' AND '2016-05-30' AND A.EmployeeID = C.EmployeeID
GROUP BY C.EmployeeId
) AS C
OUTER APPLY (
SELECT EmployeeId,
SUM(CASE WHEN TransctionTypeId = 1 THEN Amount ELSE 0 END) AS Payment,
SUM(CASE WHEN TransctionTypeId = 2 THEN Amount ELSE 0 END) AS RecoverSalary,
SUM(CASE WHEN TransctionTypeId = 3 THEN Amount ELSE 0 END) AS RecoverCash
FROM dbo.EmployeeAdvances D
WHERE A.EmployeeID = D.EmployeeID
GROUP BY EmployeeId
) AS D
WHERE A.ShowRoomId = 2

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

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
...

Selecting values of a column from multiple rows of the same table as different columns

I have a Table With the following definition :
CREATE TABLE [dbo].[Due] (
[dueID] INT IDENTITY (1, 1) NOT NULL,
[dueTypeID] INT NOT NULL,
[vehicleID] INT NOT NULL,
[dueDate] DATE NULL,
...
Here I want to generate a query which would give an output as
VehicleID Type1.dueDate Type2.dueDate Type3.dueDate ...
(the due dates should be the highest for that vehicle for that due type)
I have written the following query to do this :
select vehicleNumber, A.dueDate, B.dueDate, C.dueDate, D.dueDate, E.dueDate, F.dueDate
FROM Vehicle INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '1' GROUP BY Due.vehicleID) As A ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '2' GROUP BY Due.vehicleID) As B ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '3' GROUP BY Due.vehicleID) As C ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '4' GROUP BY Due.vehicleID) As D ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '5' GROUP BY Due.vehicleID) As E ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '6' GROUP BY Due.vehicleID) As F ON Vehicle.vehicleID = A.vehicleID
The problem is, the vehicle which does not have a due date for a particular type is taking the value of some other vehicle. Please help me figure out how this can be solved, also if I am doing this the right way or whether there is some better way to do this?
(sorry in case the question is repetitive as I tried looking for it but couldn't find the right keywords to search the problem)
Thanks a lot for helping me out.
Try this:
select vehicleNumber,
Max(case When dueTypeID = '1' Then dueDate Else null end) Typ1dueDate,
Max(case When dueTypeID = '2' Then dueDate Else null end) Typ2dueDate,
Max(case When dueTypeID = '3' Then dueDate Else null end) Typ3dueDate,
Max(case When dueTypeID = '4' Then dueDate Else null end) Typ4dueDate,
Max(case When dueTypeID = '5' Then dueDate Else null end) Typ5dueDate,
Max(case When dueTypeID = '6' Then dueDate Else null end) Typ6dueDate
FROM Due d join Vehicle v
On v.vehicleId = d.vehicleId
Group By v.vehicleNumber

Resources