【问题标题】:SQL Server - Max Date for multiple records & related dataSQL Server - 多条记录和相关数据的最大日期
【发布时间】:2016-06-14 13:09:58
【问题描述】:

我有 1900 个位置,我正在尝试查找下订单的最大(日期)。以及该相关地点/日期的订单成本和订单数量。

如何构建子查询或联接以检索此数据。

下面的示例尝试:

    select table1.location, table2.ord_dt, table2.order_cost, table2.order_qty
    from table2
    join table 3 on table2.id1 = table3.id1
    join table 1 on table1.id1 = table3.id2
    where table2.ord_dt = (
    select table1.location, max(table2.ord_dt)
    from table2
    join table 3 on table2.id1 = table3.id1
    join table 1 on table1.id1 = table3.id2
    group by table1.location

我确定我的逻辑不正确,而且我收到“谓词运算符每侧的元素数不匹配”错误。可能是因为我在主查询中需要的列多于我在子查询中的列。

感谢任何指导。

【问题讨论】:

  • 你在使用 MSSQL 吗?
  • @Backtrack 标题和标签表示是,除非 OP 很困惑,我敢肯定这不是真的 :-)
  • 您能否为每个表添加一些示例记录以及您希望示例返回的输出?

标签: sql sql-server subquery maxdate


【解决方案1】:
;with cte(location, odate) as 
(

   select table1.location, max(table2.ord_dt)
    from table2
    join table 3 on table2.id1 = table3.id1
    join table 1 on table1.id1 = table3.id2
    group by table1.location
)
select table1.location, table2.ord_dt, table2.order_cost, table2.order_qty
    from table2
    join table 3 on table2.id1 = table3.id1
    join table 1 on table1.id1 = table3.id2
    join cte on cte.location =  table1.location and cte.odate = table2.ord_dt
order by 
table1.location, table2.ord_dt, table2.order_cost, table2.order_qty

如果你使用的是MSSQL,你可以使用CTE

【讨论】:

  • 抱歉,我使用的是 SQL Server。更具体地说,我正在通过 SSIS 包构建数据流任务。
  • 我想看看 |store 1| 2016 年 6 月 13 日 | 200 美元 |第245章……商店下订单的最大日期 |订单成本|订单数量
  • @rashaad_hannah,添加订单。它会给你结果
猜你喜欢
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
相关资源
最近更新 更多