【问题标题】:Trouble getting SQL Server subquery to pick desired results无法让 SQL Server 子查询选择所需的结果
【发布时间】:2021-02-12 10:21:10
【问题描述】:

我得到了一个在 SQL Server 中使用的数据库。 这些表格是:

  • 价格(prodID、来自、价格)
  • 产品(prodID、名称、数量)
  • PO(prodID、orderID、金额)
  • 订单(orderID、日期、地址、状态、trackingNumber、custID、 船号)
  • 运费(shipID、公司、时间、价格)
  • 客户(客户 ID、姓名)
  • 地址(addrID、custID、地址)

我需要确定每个产品的 ID 和当前价格。

Price 表中的from 属性是价格更新的日期,即表中的每个 ID 都有多个价格和与之关联的日期,但 所有 ID 之间没有共同的日期 日期格式为“YYYY-MM-DD”,范围为 2018 年至 2019-12-31。

我当前的查询如下所示:

select distinct p.prodID, p.price
from Price as p
where p.[from] >= '2019-12-23' and p.[from] in (select [from]
from Price
group by [from]
having max([from]) <= '2019-12-31')
order by p.prodID;

它返回一个表格,其中包含一些 ID 的多个价格,并且完全排除了其他 ID。

有人告诉我,我需要一个子查询来执行此操作。

我认为我的查询可能过于具体,无法产生预期的结果。

我的主要目标是修复我当前的查询,以便从最近的 from 日期中选择 prodIDprice 之一。

【问题讨论】:

    标签: sql sql-server datetime sql-order-by greatest-n-per-group


    【解决方案1】:

    一个选项使用窗口函数:

    select *
    from (
        select p.*, row_number() over(partition by p.prodid order by p.from desc) rn
        from price p
        where p.from <= convert(date, getdate())
    ) t
    where rn = 1
    

    这将返回每个prodid 的最新行,其中from 不大于当前日期。

    您也可以使用with ties

    select top (1) with ties p.*
    from price p
    where p.from <= convert(date, getdate())
    order by row_number() over(partition by p.prodid order by p.from desc)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-28
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多