Status corresponding to Minimum value

Posted by Lijo on Stack Overflow See other posts from Stack Overflow or by Lijo
Published on 2010-03-27T13:18:31Z Indexed on 2010/03/27 13:23 UTC
Read the original article Hit count: 187

Filed under:

Hi Team,

I am using SQL Server 2005. I have a table as given below. There can be multiple cancellations for each FundingID. I want to select the FundingCancellationReason corrersponding to minimum date for each funding. I wrote a query as follows. It is an SQL error

1) Could you please help me to avoid the SQL Error?

2) Is there any better logic to achieve the same?

CREATE TABLE #FundingCancellation( [FundingCancellationID] INT IDENTITY(1,1) NOT NULL, [FundingID] INT , FundingCancellationDt SMALLDATETIME , FundingCancellationReason VARCHAR(50) )

SELECT FundingID, MIN(FundingCancellationDt), ( SELECT FundingCancellationReason FROM #FundingCancellation FC2 WHERE FC1.FundingID = FC2.FundingID AND FC2.FundingCancellationDt = MIN(FundingCancellationDt) ) [Reason Corresponding Minimum Date] FROM #FundingCancellation FC1 GROUP BY FundingID

-- An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

I have seen the similar approach working in a somewhat complex query. So I believe tehre will be a way to correct my query

Thanks Lijo

© Stack Overflow or respective owner

Related posts about sql