如何连接2个表但具有与表a相同的结果计数

时间:2014-12-03 14:25:36

标签: sql-server tsql

这是我所面临的困境......

我有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))

我需要加入[barcode]上的2个表格,#allItemsInBox

中每一行的最终表格中只有1个结果

请注意[#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')

1 个答案:

答案 0 :(得分: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

编辑:我更新了答案。您现在拥有与示例/问题

中指定的输出相同的输出