【问题标题】:SQL Server: Insert from second table for every unique value in first table with matching conditionSQL Server:从第二个表插入第一个表中具有匹配条件的每个唯一值
【发布时间】:2021-02-06 00:58:11
【问题描述】:

我有第一张客户数据表:

|BillTo |ShipTo_Code|Name    |Address           |ProductNum |UoM |Price  |
|:------|-----------|--------|------------------|-----------|----|-------|
|101308 |0526       |Store 1 |118 Washington St.|           |    |       |
|101308 |0542       |Store 2 |62 Central St.    |           |    |       |
|101308 |0716       |Store 3 |15 Walnut Rd.     |           |    |       |
|101308 |0817       |Store 4 |211 Sudbury Rd.   |           |    |       |

我还有第二张表,其中包含客户的产品和定价数据:

|BillTo |ProductNum |UoM |Price  |
|:------|-----------|----|-------|
|101308 |3100121    |CS  |2.90   |
|101308 |3100697    |CS  |2.45   |
|101308 |3300072    |CS  |67.80  |
|101308 |3300075    |CS  |5.45   |

我需要将定价数据插入到客户表中,以便 ShipTo_Code 中的每次更改都会显示所有 4 种产品。最终应该是这样的:

|BillTo |ShipTo_Code|Name    |Address           |ProductNum |UoM |Price  |
|:------|-----------|--------|------------------|-----------|----|-------|
|101308 |0526       |Store 1 |118 Washington St.|3100121    |CS  |2.90   |
|101308 |0526       |Store 1 |118 Washington St.|3100697    |CS  |2.45   |
|101308 |0526       |Store 1 |118 Washington St.|3300072    |CS  |67.80  |
|101308 |0526       |Store 1 |118 Washington St.|3300075    |CS  |5.45   |
|101308 |0542       |Store 2 |62 Central St.    |3100121    |CS  |2.90   |
|101308 |0542       |Store 2 |62 Central St.    |3100697    |CS  |2.45   |
|101308 |0542       |Store 2 |62 Central St.    |3300072    |CS  |67.80  |
|101308 |0542       |Store 2 |62 Central St.    |3300075    |CS  |5.45   |
|101308 |0716       |Store 3 |15 Walnut Rd.     |3100121    |CS  |2.90   |
|101308 |0716       |Store 3 |15 Walnut Rd.     |3100697    |CS  |2.45   |
|101308 |0716       |Store 3 |15 Walnut Rd.     |3300072    |CS  |67.80  |
|101308 |0716       |Store 3 |15 Walnut Rd.     |3300075    |CS  |5.45   |
etc.

这两个表之间的唯一匹配是 BillTo。

我在这里花了很多时间研究类似的问题,但还没有真正能够应用我迄今为止在线程中看到的解决方案。

This thread 给了我一个良好的开端,但它是在同一张桌子内完成的。

非常感谢任何帮助。

【问题讨论】:

  • 为什么 817 不在预期输出中?什么是逻辑?
  • 对不起,我在做桌子的时候把它漏掉了。 817 也会被表示出来。

标签: sql sql-server insert sql-insert


【解决方案1】:

这好像是join

select c.*, st.*
from customers c join
     secondtable st
     on c.billto = st.billto
order by c.shipto_code, st.productnum;

【讨论】:

  • 这很接近,但并不完全。当我运行它时,我得到了两个表的所有列以及单独行中的所有数据。我尝试将其调整为 INSERT 查询:INSERT INTO Customers (ProductNum, UoM, Price) SELECT (ProductNum, UoM, Price) FROM Price st JOIN Customers c ON c.BillTo = st.BillTo ORDER BY c.ShipTo, st.ProductNum' 并将其插入到正确的列中,但将所有内容都放在新行中。
  • @adgy 。 . .只需选择您想要的列。
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多