好吧,很难在单个主题行中描述我需要从 SQL 中获得什么。我希望这个主题不会让太多人望而却步......
我有两张表,一张包含船舶 ID、追踪号码和运费。
Declare @ship as table
(
shipID varChar(25),
TrkID VarChar(50),
shp_Cost money
)
Insert into @ship Values('1000000058','075637240645964',13.1900)
Insert into @ship Values('1000000077','075637240646671',10.3300)
Insert into @ship Values('1000000078','075637240646695',12.8300)
Insert into @ship Values('1000000079','075637240646725',11.2100)
这具有 1:Many 关系,其中这是一次发货,但其中可能包含许多行项目。第二个表有行项目,出于演示原因,它看起来像这样......
Declare @ship_2 as table
(
shipID VarChar(25),
trkID VarChar(50),
Item_SKU VarChar(50),
Ship_Quantity int
)
Insert into @ship_2 Values('1000000058','075637240645964','P025.3',25)
Insert into @ship_2 Values('1000000058','075637240645964','P100.1',25)
Insert into @ship_2 Values('1000000058','075637240645964','P21.1',25)
Insert into @ship_2 Values('1000000058','075637240645964','P024',25)
Insert into @ship_2 Values('1000000058','075637240645964','A-P927',25)
Insert into @ship_2 Values('1000000058','075637240645964','PBC',500)
Insert into @ship_2 Values('1000000077','075637240646671','P213.99',25)
Insert into @ship_2 Values('1000000077','075637240646671','P029',25)
Insert into @ship_2 Values('1000000077','075637240646671','P-05.3',25)
Insert into @ship_2 Values('1000000078','075637240646695','P0006.1',25)
Insert into @ship_2 Values('1000000078','075637240646695','P01.67-US',25)
Insert into @ship_2 Values('1000000078','075637240646695','P09.1',25)
Insert into @ship_2 Values('1000000078','075637240646695','P022.1',25)
Insert into @ship_2 Values('1000000078','075637240646695','P08.3',25)
Insert into @ship_2 Values('1000000079','075637240646725','P02',25)
Insert into @ship_2 Values('1000000079','075637240646725','P0006.1',25)
Insert into @ship_2 Values('1000000079','075637240646725','P1.4',25)
所以我需要的是一种连接两个表并提供运输详细信息以将运输成本包含在一个结果集中的方法。除非您认为只有其中一项需要承担运费,否则这并不是一个真正的问题。如果有 6 个行项目,我只需要返回第一个行项目的运费,其余 5 行返回 0。
我目前完全不知道如何才能实现这一目标。一切都在存储过程中,我可以根据需要创建临时表或声明表。
任何人都可以对我需要寻找的内容提出建议。
感谢您为我们的指导提供的任何帮助。
蒂姆
最佳答案
为什么不使用 CTE 来实现此目的:
;with cte as
(
select s.shipID,
s.TrkID,
s.shp_Cost,
s2.Item_SKU,
s2.Ship_Quantity,
ROW_NUMBER() over(PARTITION by s.shipid order by s.shipid) rn
from @ship s
inner join @ship_2 s2
on s.shipID = s2.shipID
)
select shipID,
TrkID,
case when rn = 1 then shp_Cost else 0 end shp_cost,
Item_SKU,
Ship_Quantity
from cte
关于T-SQL 查询,连接两个表,但仅返回表 1 中第二个表中的 1 行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11940466/