在SQL 2005存储过程中,我需要运行包含1-M的查询。我需要只返回许多表中的一个,即最早的日期。
我看过In SQL how do I write a query to return 1 record from a 1 to many relationship?
和SQL conundrum, how to select latest date for part, but only 1 row per part (unique)
但我不确定在我的情况下什么是最好的解决方案,因为我还在使用Insert Into临时表并使用动态排序和分页。
这是我的SQL。我想要的是返回很多行的Foo,但只有我传入的起始和结束数据参数之间最早的b.CreatedDate,其中每个Foo的Bar通常大约有5行。
DECLARE @StartDate datetime
DECLARE @EndDate datetime
INSERT INTO @Results
SELECT distinct
f.Name,
f.Price
b.CreatedDate ,
// loads more columns removed for brevity
FROM
foo f
join bar b on f.Id = b.fooId
// loads more table removed for brevity
WHERE
(@x is null OR f.Id = @x)
AND (@Deal is null OR f.IsDeal = @Deal)
AND (@StartDate is null OR sd.SailingDate >= @StartDate)
AND (@EndDate is null OR sd.SailingDate <= @EndDate)
// loads more filters removed for brevity
declare @firstResult int, @lastResult int
set @firstResult = ((@PageNumber-1) * @ItemsPerPage) + 1;
set @lastResult = @firstResult + @ItemsPerPage;
select @TotalResults = count(1) from @Results;
WITH ResultItems AS
(
SELECT *, ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @SortBy = 'priceLow' THEN Price END ASC,
CASE WHEN @SortBy = 'Soonest' THEN CreatedDate END ASC,
CASE WHEN @SortBy = 'priceHigh' THEN Price END DESC
) As RowNumber
FROM @Results r
)
SELECT * from ResultItems
WHERE RowNumber >= @firstResult AND RowNumber < @lastResult
ORDER BY
CASE
WHEN @SortBy = 'priceHigh' THEN (RANK() OVER (ORDER BY Price desc))
WHEN @SortBy = 'priceLow' THEN (RANK() OVER (ORDER BY Price))
WHEN @SortBy = 'Soonest' THEN (RANK() OVER (ORDER BY CreatedDate ))
END
此查询将返回多个'b.CreatedDate'而不是我的过滤器之间最早的一个
更新 所以我想看看 如果我的源数据是:
Foo
___
1 , Hello
2 , There
Boo
___
1, 1, 2011-2-4
2, 1, 2011-3-6
3, 1, 2012-12-21
4, 2, 2012-11-2
结果将是
1, Hello,2011-2-4
2, There, 2012-11-2
答案 0 :(得分:0)
我想我只是通过在我的查询顶部添加CTE来实现它
;with cteMinDate as (
select FooId, min(CreatedDate) As CreatedDate
from Bar WHERE
(@StartDate is null OR CreatedDate>= @StartDate)
AND (@EndDate is null OR CreatedDate<= @EndDate)
group by FooId
)
与此处SQL conundrum, how to select latest date for part, but only 1 row per part (unique)相同。这样做可以让我从主查询中删除日期查询部分,只在CTE中执行一次