Tsql T-SQL查询,连接两个表,但仅从表1返回第二个表中1行的数据

Tsql T-SQL查询,连接两个表,但仅从表1返回第二个表中1行的数据,tsql,sql-server-2008-r2,Tsql,Sql Server 2008 R2,好的,很难在一个主题行中描述我需要从SQL中得到什么。我希望这个话题不会让太多人反感 我有两张表,一张有船号、追踪号和运费 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('100

好的,很难在一个主题行中描述我需要从SQL中得到什么。我希望这个话题不会让太多人反感

我有两张表,一张有船号、追踪号和运费

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

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

任何人都有我需要寻找的建议

感谢您对我们的帮助和指导


Tim

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

请参见。。。SQLServer2008R20这工作得很好!谢谢现在我要出发去了解更多关于CTE的知识,以及我可以在哪里使用它。