基本上,我有两个旧表,一个新表,通过匹配ID作为参考来合并两者的一部分。
一个旧表名为“ items_table ”,其中包含以下列: “材料”(我用作ID来导航到项目),“条件”,“数量”,“描述”(以及一些我现在不使用的其他不相关的列)
第二个旧表的名称为“ price_table ”,其中包含:“ ItemNum”,“ itemtype”,“ _ subtype”,“ FullPrice”(以及我不想包含的其他列)新表)
第三个新的临时表名为“ Items4sale ”,其中应包含以下列(值是通过查询从旧表中插入的):“ ID”,“ _ Type”,“子类型” ,“条件”,“描述”,“数量”,“全价”,“价格”(这是一个新的计算值),“ PotentiaPrice”(这是一个新的计算值)
这是代码:
if object_id('Items4sale') is not null /* <--- creating the new table */
drop table Items4sale;
create table Items4sale (
ID int,
_Type NVARCHAR(100),
Subtype NVARCHAR(100),
Condition INT,
Descr NVARCHAR(100),
Quantity INT,
FullPrice float, /* <--- I actually want to limit the display for prices, for example to "3299.33" instead of "3299.332120" */
Price float,
PotentialPrice float
)
INSERT INTO Items4sale (ID, _Type, Subtype, FullPrice) /* Inserting here columns from "price_table" */
SELECT [ItemNum], [itemtype], [_subtype], [FullPrice]
FROM price_table WHERE [ItemNum] in (SELECT [Material] from items_table) /* Same ID of the item should match to one in the items_table */
INSERT INTO Items4sale (ID, Condition, Quantity, Descr) /* Inserting here columns from "items_table" */
SELECT [Material] (same for ID), [site_loc], [limit], [descriptions]
FROM items_table WHERE cast([site_loc] as CHAR(50)) like '%8'; /* Use only if "site_loc" column (to insert in "Condition" in the new table) ends with "8" ("5338" for example is OK and should be included) */
UPDATE Items4sale set Price=FullPrice*0.05
UPDATE items4sale set PotentialPrice=Price*Quantity
SELECT * FROM Items4sale
这就是我得到的结果:
ID | _Type | Subtype | Condition | Descr | Quantity | FullPrice | Price | PotentialPrice
189 | Plastic | Toy | NULL | NULL | NULL | 8 | 0.4 | NULL
.........
注意“ Condition”,“ Descr”,“ Quantity和“ PotentialPrice”如何以NULL出现。那些匹配的列(如上面代码中的INSERT)在“ items_table”中的ID不为null是“ 189”。
这是我想要的结果:(示例)
ID | _Type | Subtype | Condition | Descr | Quantity | FullPrice | Price | PotentialPrice 189 | Plastic | Toy | 3998 *(ends with '8')* | A plastic toy | 4 | 8 | 0.4 | 1.6 .........
我该如何解决?
另外,我的问题的第二部分-这是我运行以测试错误的查询,(上面的代码除外):
SELECT * FROM Items4sale WHERE ID = 189;
SELECT * FROM items_table WHERE [Material] = 189;
上面是查看我的第一个查询中是否缺少任何重复的ID。 事实证明,在“ items_table”中有多个“ 189”作为“ Material”(物料的ID) 因此,从上面代码的第二个“ SELECT”中,我得到几行以“ 189”作为Material(ID),因为实际上存在多个行-我没有考虑到名为“ Location”(NVARCHAR(100 ))。我认为这是更高级的:如果在“ items_table”中有多个行具有ID,则不要将它们合并到“ Items4sale”(合并后的新表)中的一行中,而是将它们创建为ID =“ 189”,“(1)189”,“(2)189”(就像Windows尝试两次创建相同的文件/文件夹时一样),但它们的“条件”(items_table。[site_loc])在此大小写不以“ 8”结尾。我仍然想列出它们并从“ price_table”中应用它们的价格等。
这很重要,因为项目可能相同(具有相同的条形码/ ID),但具有不同的“位置”,因此也可能具有不同的“数量”。
答案 0 :(得分:0)
您的尝试失败了,因为基本上,您正在运行2条insert语句,而只想生成一条记录。
虽然应该可以首先从一个表中的列开始insert
,然后从另一个表中的列开始update
,但使用{{1 }}查询:
insert ... select
无关的注释:根据我对您的用例的理解(您想显示派生的信息),此查询将更适合视图;这为您提供了有关联接数据的最新信息,(另一方面,表需要手动更新,这可能会很乏味)。