Status corresponding to Minimum value
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 开发者_JAVA技巧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
This query will return the Reason (and any other columns you may want) for each minimum date for each FundingID:
SELECT FC1.FundingID, FC1.FundingCancellationDt,
FC1.FundingCancellationReason, FC1.OtherColumn1, FC1.Other...
FROM #FundingCancellation FC1
JOIN
(
SELECT FundingID, MIN(FundingCancellationDt) as 'MinDate'
FROM #FundingCancellation
GROUP BY FundingID
) AS Grouped ON (Grouped.FundingID = FC1.FundingID
AND (Grouped.MinDate = FC1.FundingCancellationDt
OR Grouped.MinDate IS NULL))
Note that if a given FundingID has more than one row with the same FundingCancellationDt (and it is the minimum), this will return ALL reasons for that minimum date.
The "OR Grouped.MinDate IS NULL" allows for null dates.
If you have duplicate minimum dates for a FundingID and you still want only one of the Reasons for each minimum, then use this:
SELECT FundingID, MinDate,
(SELECT TOP 1 FundingCancellationReason
FROM #FundingCancellation
WHERE FundingCancellationDt = Grouped.MinDate) as 'Reason'
FROM
(
SELECT FundingID, MIN(FundingCancellationDt) as 'MinDate'
FROM #FundingCancellation
GROUP BY FundingID
) AS Grouped
精彩评论