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

时间:2012-08-13 18:51:40

标签: 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('1000000077','075637240646671',10.3300)
Insert into @ship Values('1000000078','075637240646695',12.8300)
Insert into @ship Values('1000000079','075637240646725',11.2100)

这有一个1:很多关系,这是一个货件,但它可能有很多行项目。第二个表有行项目,出于演示原因,它看起来像这样......

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。

我目前完全失去了如何实现这一目标。它将全部存储在proc中,我可以根据需要创建临时表或声明表。

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

感谢您提供的任何帮助。

1 个答案:

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

相关问题