2014-12-03 52 views
-1

這裏我遇到的困境......如何加入2個表,但有相同的結果算表

我有2個表

create table #orders 
(orderNumber int,qty int,sku varchar(250),barcode varchar(250)) 

create table #allItemsInBox 
([id] int,[date] date,[localsku] varchar(250),[box] varchar(250),barcode varchar(250)) 

我需要在加入2個表[barcode]和只有1個結果的每一行的決賽桌#allItemsInBox

請注意[#allItemsInBox].[id]是獨一無二的[#allItemsInBox]其他字段可能不

我將如何去做這樣的事情?

sample data: 
[#orders] 
(1,0,'10','10') 
(1,0,'20','20') 
(3,0,'20','20') 
(4,0,'30','30') 
(5,0,'40','40') 
(6,0,'50','50') 

#allItemsInBox 
(1,'12/3/2014',10,'Box1',10) 
(2,'12/2/2014',20,'Box2',20) 
(3,'12/1/2014',20,'Box3',20) 
(4,'11/30/2014',20,'Box4',20) 
(5,'11/29/2014',30,'Box5',30) 
(6,'11/28/2014',40,'Box6',40) 
(7,'11/27/2014',60,'Box8',60) 
(8,'11/27/2014',50,'Box10',50) 

#output 
(ordernumber int,uniqueitemID int,localsku varchar(250),box varchar(250)) 
(1,1,10,'Box1') 
(1,2,20,'Box2') 
(3,3,10,'Box3') 
(4,5,30,'Box5') 
(5,6,40,'Box6') 
(6,8,50,'Box10') 
+0

你怎麼想,當有多個訂單具有相同的條碼,以顯示你現在有相同的輸出?數它們? – 2014-12-03 14:29:04

+0

每個訂單上的每個商品都必須具有唯一的'[#allItemsInBox]。[id]' – Ishey4 2014-12-03 14:30:41

+0

您可以發佈樣本數據以及所需的輸出。 – Rahul 2014-12-03 14:30:52

回答

1

這很快但很有效。根據數據的大小,這可能不是性能最好的方式。但是,這會給你一個開始在

DECLARE @orders TABLE (
    orderNumber int, 
    qty int, 
    sku varchar(250), 
    barcode varchar(250) 
) 


DECLARE @allItemsInBox TABLE (
    [id] int, 
    [date] date, 
    [localsku] varchar(250), 
    [box] varchar(250), 
    barcode varchar(250) 
) 

INSERT INTO @orders VALUES 
    (1,0,'10','10'), 
    (1,0,'20','20'), 
    (3,0,'20','20'), 
    (4,0,'30','30'), 
    (5,0,'40','40'), 
    (6,0,'50','50') 

INSERT INTO @allItemsInBox VALUES 
    (1,'2014-12-03',10,'Box1',10), 
    (2,'2014-12-02',20,'Box2',20), 
    (3,'2014-12-01',20,'Box3',20), 
    (4,'2014-11-30',20,'Box4',20), 
    (5,'2014-11-29',30,'Box5',30), 
    (6,'2014-11-28',40,'Box6',40), 
    (7,'2014-11-27',60,'Box8',60), 
    (8,'2014-11-27',50,'Box10',50) 

SELECT 
    orders.orderNumber AS ordernumber 
    ,(SELECT TOP 1 allItems.id FROM @allItemsInBox allItems WHERE allItems.barcode = orders.barcode AND allItems.id >= orders.orderNumber ORDER BY allItems.id) AS uniqueitemID 
    ,(SELECT TOP 1 allItems.localsku FROM @allItemsInBox allItems WHERE allItems.barcode = orders.barcode AND allItems.id >= orders.orderNumber ORDER BY allItems.id) AS localsku 
    ,(SELECT TOP 1 allItems.box FROM @allItemsInBox allItems WHERE allItems.barcode = orders.barcode AND allItems.id >= orders.orderNumber ORDER BY allItems.id) AS box 
FROM 
    @orders orders 

結果:

ordernumber uniqueitemID localsku box 
1 1 10 Box1 
1 2 20 Box2 
3 3 20 Box3 
4 5 30 Box5 
5 6 40 Box6 
6 8 50 Box10 

編輯:我更新了答案。當你在你的例子/問題指定

+0

在這種情況下,我唯一ID的訂單號碼1和3是一樣的...它必須是不同的...... – Ishey4 2014-12-03 15:07:16

+0

我更新了答案 – user1200271 2014-12-03 15:14:16

+0

我用不同的項目/訂單跑了這一點,並發現當2個數量有同樣的物品在他們我得到相同的項目回 – Ishey4 2014-12-03 15:28:50

相關問題