0

以下代码:

    select(

    select m.Code + '   ' + cast(m.Completed as varchar(max)) + '   '+ cast(ol.Billed as varchar(max)) + '  ' + cast(m.Delete as varchar (max)) 
    from matterdetails as m
    full join officeledger as ol on ol.id=m.id
    order by ol.Billed desc 

    for xml path(''))

返回结果

    Code       Completed     Billed        Deleted
    --------   -----------   -----------   -----------
    HK168/03   Mar 30 2012   Aug 17 2011   Mar 30 2012
    HK168/03   Mar 30 2012   Feb 24 2011   Mar 30 2012
    HK168/03   Mar 30 2012   Dec 23 2010   Mar 30 2012
    FT080/03   Apr  4 2012   Mar 29 2012   Apr  4 2012
    FT080/03   Apr  4 2012   Feb  9 2012   Apr  4 2012
    FT080/03   Apr  4 2012   Oct 20 2011   Apr  4 2012

    etc.

而我需要结果

    Code       Completed     Billed        Deleted
    --------   -----------   -----------   -----------
    HK168/03   Mar 30 2012   Aug 17 2011   Mar 30 2012
    FT080/03   Apr  4 2012   Mar 29 2012   Apr  4 2012

    etc.

我知道我必须在select top 1某处插入以限制ol.Billed结果,但我不确定在哪里。任何建议都会很棒。

4

2 回答 2

1

试试这个:它将加入每个 ID 的最大账单日期

   select(
    select m.Code + '   ' + cast(m.Completed as varchar(max)) + '   '+ cast(ol.Billed as varchar(max)) + '  ' + cast(m.Delete as varchar (max)) 
    matterdetails as m
    full join (select id, Max(billed) as 'Billed' from officeledger) as ol on ol.id=m.id
        order by ol.Billed desc 
for xml path(''))
于 2012-06-21T13:27:46.293 回答
1

你可以替换:

full join officeledger as ol on ol.id=m.id

和:

full join (select id,MIN(Billed) as Billed from officeledger group by id) as ol = ol.id = m.id

也应该有一种方法可以做到这一点ROW_NUMBER(),但除非你需要它,否则我不会写它。

于 2012-06-21T13:29:04.817 回答