Search code examples
sql-serversubquerysql-server-2016

Error in Select multi Column from Subquery


I wrote following SQL command

select * from [Monitoring].[dbo].[MaintTaskMonitor]  
where (JobStartDate,TaskType) in (
select max(JobStartDate),TaskType  from [Monitoring].[dbo].[MaintTaskMonitor]  where systemname='Dido'
group by TaskType) 

which gave the following error:

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

Where is the problem from?


Solution

  • You could, instead, switch to a correlated subquery and then check the value of JobStartDate from the outer scope matches the MAX value of the inner scope in the HAVING:

    USE Monitoring; --Connect to the correct database instead, no need for 3 part naming
    GO
    
    SELECT <Explicit Column List> --Get out of the habit of using *
    FROM [dbo].[MaintTaskMonitor] MTM
    WHERE EXISTS (SELECT 1
                  FROM [dbo].[MaintTaskMonitor] sq
                  WHERE sq.systemname = 'Dido'
                    AND sq.TaskType = MTM.TaskType
                  HAVING MAX(sq.JobStartDate) = MTM.JobStartDate);