如何获取最后一个基于插入值的ID,该ID源自另一个表?

时间:2018-10-22 23:26:59

标签: sql sql-server tsql

从中获取最后一个Occurance的最便捷方法是 @TempTable2基于QuoteID DESC中的@TempTable1

预期结果应该是:

enter image description here

declare @TempTable1 table (QuoteID int, QuoteGUID varchar(50), PolicyNumber varchar(100), Premium money)
insert into @TempTable1 values   (1, 'ABC1','Policy1',100)
                                ,(2, 'ABC2','Policy1',200)
                                ,(3, 'ABC3','Policy1',300)
                                ,(11, 'ABC11','Policy2',150)
                                ,(22, 'ABC22','Policy2',250)
                                ,(33, 'ABC33','Policy2',350)



declare @TempTable2 table (QuoteGUID varchar(50), Occurance money)
insert into @TempTable2 values   ('ABC1',1000)
                                ,('ABC2',2000)
                                ,('ABC3',3000)
                                ,('ABC11',1500)
                                ,('ABC22',2500)
                                ,('ABC33',3500)
--select * from @TempTable2
--select * from @TempTable1
select
     PolicyNumber 
    ,sum(Premium) as Premium
--How can I get the last Occurance from @TempTable2  based on QuoteID DESC from @TempTable1?
    --,t2.Occurance
from @TempTable1 t1
        inner join @TempTable2 t2 ON t1.QuoteGUID = t2.QuoteGUID
group by PolicyNumber 

3 个答案:

答案 0 :(得分:2)

;WITH x AS 
(
  SELECT PolicyNumber, 
    Premium = SUM(Premium) OVER (PARTITION BY PolicyNumber), 
    QuoteGUID, 
    rn = ROW_NUMBER() OVER (PARTITION BY PolicyNumber ORDER BY QuoteID DESC)
  FROM @TempTable1 
)
SELECT x.PolicyNumber, x.Premium, y.Occurance
FROM x
INNER JOIN @TempTable2 AS y
ON x.QuoteGUID = y.QuoteGUID
WHERE x.rn = 1;

答案 1 :(得分:2)

另一个选择是使用窗口功能First_Value()

示例

Select PolicyNumber 
      ,Premium = sum(Premium)
      ,Occuance = max(Occuance)
 From (
        select PolicyNumber 
              ,Premium 
              ,Occuance = first_value(Occurance) over (Partition By PolicyNumber Order by QuoteID desc )
        from @TempTable1 t1
                inner join @TempTable2 t2 ON t1.QuoteGUID = t2.QuoteGUID
      ) A
 Group by PolicyNumber 

返回

PolicyNumber    Premium Occuance
Policy1         600.00  3000.00
Policy2         750.00  3500.00

答案 2 :(得分:0)

在SQL Server中,我将使用apply

select t1.PolicyNumber, t1.Premium, t2.occurance
from @TempTable1 t1 outer apply
     (select top 1 t2.*
      from @TempTable2 t2 
      where t1.QuoteGUID = t2.QuoteGUID
      order by t2.QuoteID desc
     ) t2;

您的样本表没有QuoteId。而且我认为不需要任何汇总。