我必须在2个产品之间创建一个关联,它具有唯一的product_ids并将它们插入到已构造的表中。该关联是基于这些产品ID所具有的唯一部件号创建的。例如:
Product_id = 7578711 Part Number = 0101-2478 Product Id = 7957948 Part Number = 0101-2478 Product Id = 10558140 Part Number = 0101-2478
我当前的表格包含以下列:
ID (int) identity (1, 1)
product_id
date
guid
其中数据的格式为:
1, 7578711, 12345, 2010-08-24 04:29:04.000,00286AFB-3880-4085-BAA0-DBCC0D59A391
我有一个查询,它能够将Product_id滚动到零件号级别,然后查询以将零件号滚动到product_id级别。
基于以上数据,如果它们具有相同的部件号,我想创建一个关联并生成插入语句,它将以下列形式添加2条记录:
2, 7957948, 12345, 2010-08-24 04:29:04.000,00286AFB-3880-4085-BAA0-DBCC0D59A391
3, 10558140, 12345, 2010-08-24 04:29:04.000,00286AFB-3880-4085-BAA0-DBCC0D59A391
该表中将有许多产品ID。以上只是一个例子:
我有2个公用表格表达式:1将产品ID滚动到零件编号级别,另一个将零件编号回滚到多个产品ID。我试图避免光标。
这里的任何人都可以帮我解决这个问题吗?
我的2个CTE如下:
;WITH cte (product_id, item_number)
AS
(
SELECT DISTINCT --TOP 1000
pds.product_id
--,pd.productOwner_id
, i.item_number
FROM SurfwatcherEndeavorStats.dbo.productDetailBySite pds WITH ( NOLOCK )
INNER JOIN ProductData.dbo.productDimensions pd with ( NOLOCK ) ON pds.product_id = pd.product_id
INNER JOIN ProductData.dbo.options o with ( NOLOCK ) ON pds.product_id = o.product_id
INNER JOIN ProductData.dbo.items i with ( NOLOCK ) ON o.option_id = i.item_id
WHERE pds.productDetail_date > DATEADD(yyyy, -1, GETDATE())
AND i.item_number IS NOT NULL
--AND i.item_number = '0101-3258'
)
SELECT TOP 1 item_number
FROM cte WITH (NOLOCK)
WHERE product_id = 7957948
;WITH cte1 (product_id, item_number)
AS
(
SELECT DISTINCT --TOP 1000
pds.product_id
--,pd.productOwner_id
, i.item_number
FROM SurfwatcherEndeavorStats.dbo.productDetailBySite pds WITH ( NOLOCK )
INNER JOIN ProductData.dbo.productDimensions pd with ( NOLOCK ) ON pds.product_id = pd.product_id
INNER JOIN ProductData.dbo.options o with ( NOLOCK ) ON pds.product_id = o.product_id
INNER JOIN ProductData.dbo.items i with ( NOLOCK ) ON o.option_id = i.item_id
WHERE pds.productDetail_date > DATEADD(yyyy, -1, GETDATE())
AND i.item_number IS NOT NULL
)
SELECT product_id
FROM cte1 WITH (NOLOCK)
WHERE item_number = '0101-2478'
答案 0 :(得分:-1)
试试这个Sql。它应该为您提供两个使用相同部件号的产品之间所有关联的完整列表......这就是您想要的吗?
Select Distinct A.Product_Id, B.Product_ID
From YourTable A
Join YourTable B
On B.PartNumber = A.PartNumber
And B.Product_Id > A.Product_Id