【问题标题】:joining 3 tables with data from each to be returned将 3 个表与每个要返回的数据连接起来
【发布时间】:2014-03-31 21:11:24
【问题描述】:

需要帮助以根据 3 个不同的日期从 3 个不同的表中捕获记录。应包括来自任何表的任何事务,并在可能的情况下合并结果: 样本数据

Table 1 sales table
Item#, Sold Date, invoice, etc.
111, 1/2/14, poabc
222, 1/3/14, poedf
123, 1/4/14, poxyz

Table 2 process table
Item#, proc Date, paid amt, etc.
111, 1/12/14, 12
456, 1/25/14, 16 

Table 3 canceled table
Item#, cancel date, reason, etc.
222, 1/8/14, reason1
555, 1/9/14, reason2

结果应包括在某个日期范围内已售出、处理或取消的任何商品,每行一行 - 示例结果
商品编号、销售日期、处理日期、取消日期、原因等。

111, 1/2/14, 1/12/14, (null) , (null) ,
222, 1/3/14, (null) , 1/8/14, reason1
123, 1/4/14, (null) , (null) , (null) ,
456, (null), 1/25/14, (null) , (null) ,
555, (null) , (null) ,1/9/14, reason2

不知道如何处理、联合、连接等。尝试了一个基于 item#s 的视图,在 proc = sold(+) 和 proc = cancelled(+) 上的左外部,然后将其与第二个联合起来取消的项目编号不在上面,左外取消 = proc(+) 和取消 = sold(+) 和 (proc IS NULL and sold IS NULL) 然后呢?不确定这是最好的方法或如何设置它

【问题讨论】:

    标签: sql join union union-all


    【解决方案1】:

    您可以使用大多数数据库支持的full outer join 来执行此操作。

    select coalesce(s.item, p.item, ) as item,
           s.SoldDate, p.procDate, c.cancelledDate, c.reason
    from sales s full outer join
         process p
         on p.item = s.item full outer join
         cancelled c
         on c.item = coalesce(s.item, c.item);
    

    【讨论】:

    • 我还有另外 3 个表要加入,以添加地址和电话等详细信息,那么我可以继续添加到 from 语句吗?
    • 如果它们只有行的子集,你可以做同样的事情。 . .但请记住为每个条件扩展coalesce()
    • 其他表的键值会有所不同,大多数是从项目中删除的 # 但有些会从客户 # 中删除,例如,
    • coalesce 只是加入这 3 个表的键??
    • @user3363178 。 . .它是 full outer join 中之前表格中的 id 列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2022-07-04
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多