【问题标题】:Combine 2 SQL Server Tables in one table将 2 个 SQL Server 表合并到一个表中
【发布时间】:2013-06-10 19:01:55
【问题描述】:

我有 2 个 SQL Server 表发票和生产。 Invoice 包含这些列(ID、ItemID、Date、AccountNo、Quantity、Type、Price、Total),Production Table 包含这些列(ItemID、Date、Quantity、Type) 我想将这两个表组合在一个表中,其中 ItemID、Date 和 Quantity 是常见的。就像要在发票数据之后查看的生产日期,然后我按日期排序。并且非公共字段可以具有NULL值)与以下示例相同...

怎么做?

ID      ItemID     Date          AccountNo      Quantity     Type         Price    Total
------------------------------------------------------------------------------------------
1       4          2013-06-10    123456         10           Invoice      5.00     50.00
2       7          2013-06-10    456789         15           Invoice      3.00     45.00
NULL    4          2013-06-05    NULL           40           Production   NULL     NULL

【问题讨论】:

    标签: c# sql-server winforms


    【解决方案1】:

    你想做一个full outer join

    select i.ID,
           coalesce(i.ItemID, p.ItemId) as ItemId,
           coalesce(i.Date, p.Date) as Date,
           i.AccountNo,
           coalesce(i.Quantity, p.Quantity) as Quantity,
           p.Type, i.Price 
    from Invoice i full outer join
         Production p
         on i.ItemID = p.ItemId and
            i.Date = p.Date and
            i.Quantity = p.Quantity
    

    当第二个表在第一个中没有匹配时,coalesce() 确保键列来自第二个表。

    【讨论】:

    • @Gordan,我正在尝试按 ItemId 过滤,它给出了一个错误 Ambiguous column name 'ItemId'!。就像我在写'ItemId = 1'。如何过滤?
    • 您需要为其添加一个或其他表别名。因为这是full outer join,所以最好是coalesce(i.ItemId, p.ItemId) = 1
    猜你喜欢
    • 1970-01-01
    • 2018-01-10
    • 2020-12-13
    • 1970-01-01
    • 2022-01-21
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多