XML路径中的SQL Top 1('')

时间:2012-06-21 13:16:56

标签: sql sql-server

以下代码:

    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结果,但我不确定在哪里。任何建议都会很棒。

2 个答案:

答案 0 :(得分: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(''))

答案 1 :(得分: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()执行此操作,但除非您需要,否则我不会编写它。