在一个查询中混合聚合和前1

时间:2016-05-11 18:43:09

标签: sql-server sql-server-2012

在下面的选择中我有 2汇总 5 top 1 字段

select *
from (
       select sum(case when field2 = 1 then 1 end) over (partition by field0) as field5,
              max(case when field3 = 1 then field4 end) over (partition by field0) as field6,
              -- above is 2 aggregates

              -- below is select 5 fields based on top 1 order by desc
              row_number() over (partition by field0 order by field1 desc) as rowNum
              field0,
              field1,
              field2,
              field3,
              field4
       from table1
        --in my case i'm doing an innser join on field0 on an inserted table from a trigger
  ) x
-- below is the top 1 related filter
where x.rowNum = 1

有更好的方法来写这个吗? (意味着执行计划更快和/或语法更好)

执行计划的当前部分 current section of the execution plan

1 个答案:

答案 0 :(得分:0)

这应该稍微优化一下:

select field0,
    field1,
    field2,
    field3,
    field4,
    field5,
    field6
from (
    select field0,
        sum(case when field2 = 1 then 1 end) as field5,
        max(case when field3 = 1 then field4 end) as field6,
    from table1
    group by field0
) t1
cross apply
(
    select top 1 field1,
        field2,
        field3,
        field4
    from table1 t2
    where t2.field0 = t1.field0
    order by field1 desc
) ca