【问题标题】:Get Products By Minimum Duration Between StartDate and EndDate?通过 StartDate 和 EndDate 之间的最短持续时间获取产品?
【发布时间】:2014-09-04 20:07:14
【问题描述】:

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

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 条记录?

【问题讨论】:

    标签: sql sql-server


    【解决方案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
    

    【讨论】:

    • 谢谢 它仅适用于 1 个产品 (id=1)。我也需要为其他产品这样做
    • 谢谢我用 Min 和 Group By 修复它
    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多