通过StartDate和EndDate之间的最短持续时间获取产品?

时间:2014-09-04 11:20:23

标签: sql sql-server

我遇到一些问题,需要在开始数据和结束日期以及最短持续时间之间获得不同的产品。我的表结构是,

ID   SKU   Desc1   Desc2   Price   PriceFrom   PriceTo
-------------------------------------------------------
1    xxxx  xxxx     xxxx     12     1/1/2014    1/1/2015    
1    xxx   xxxx     xxxx     12     1/1/2014    2/1/2014    
1    xxx   xxxx     xxxx     12     9/1/2014    10/1/2014

让我们说今天的日期是09/04/2014。所以我们有2个选项记录1和3(因为2超出了今天的范围),但我选择3,因为第3个记录的持续时间少于第1个记录?

1 个答案:

答案 0 :(得分:1)

您可以使用order bytop

来执行此操作
select top 1 t.*
from table t
where cast(getdate() as date) >= PriceFrom and cast(getdate() as date) <= PriceTo
order by datediff(day, PriceFrom, PriceTo) asc;

<强>更新

SELECT
    MIN(DATEDIFF(DAY, t.PriceFrom, t.PriceTo)),
    t.ID,
    t.Name,
    t.ModelNumber,
    t.Description,
    t.Price,
    t.NewPrice,
    t.SKU
FROM Products t
WHERE GETDATE() BETWEEN PriceFrom AND PriceTo
GROUP BY    t.ID,
            t.Name,
            t.ModelNumber,
            t.Description,
            t.Price,
            t.NewPrice,
            t.SKU
相关问题