【发布时间】:2020-03-09 23:40:52
【问题描述】:
基本上我有两个旧表,一个新表通过匹配 ID 作为参考来组合两者的一部分。
一个旧表名为“items_table”并包含以下列: “Material”(我用它作为 ID 导航到项目)、“Condition”、“Quantity”、“Desc”(还有一堆其他不相关的列,我现在不使用)
第二个旧表名为“price_table”,包含:“ItemNum”、“itemtype”、“_subtype”、“FullPrice”(以及更多我不想包含在我的新表)
还有第三个新的临时表,名为“Items4sale”,应包含以下列(通过查询从旧表中插入值):“ID”、“_Type”、“Subtype” ", "Condition", "Desc", "Quantity", "FullPrice", "Price" (这是一个新的计算值), "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”是“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”作为材料(ID)的行,因为实际上不止一个 - 我没有考虑名为“Location”的列(NVARCHAR(100 )) 在此表中。我相信这有点高级:如果在“items_table”中有不止一行具有 ID,则不要将它们组合到“Items4sale”(组合的新表)中的一行,而是将它们创建为ID = "189", "(1)189", "(2)189" (就像 Windows 在您尝试创建两次相同的文件/文件夹时所做的那样)但它们的“条件”(items_table.[site_loc])在此case 不以“8”结尾。我仍然想列出它们并从“price_table”中应用它们的价格等。
这很重要,因为商品可能相同(具有相同的条形码/ID),但“位置”不同,因此“数量”也可能不同。
【问题讨论】:
-
请阅读this,了解一些改进问题的技巧。
标签: sql sql-server tsql sql-update sql-insert