2

好的,很难在一个主题行中描述我需​​要从 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。

我目前完全不知道如何做到这一点。它将全部存储在存储过程中,我可以根据需要创建临时表或声明表。

任何人都对我需要寻找什么有建议。

感谢您提供的任何帮助我们的指导。

蒂姆

4

1 回答 1

3

为什么不为此使用 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

请参阅带有演示的 SQL Fiddle

于 2012-08-13T18:59:36.070 回答