我的视图表是这样的:
position price orderid buylog otherlog
1         15   100     08:00  08:01
2         15   100     08:00  08:02
2         15   100     08:00  08:05
2         15   100     08:00  08:02
2         15   101     08:10  08:15
2         15   101     08:10  08:12
2         15   102     08:20  08:25
2         15   103     08:30  08:31
2         15   103     08:30  08:32
2         15   103     08:30  08:33
预期结果:
position price orderid buylog otherlog
1         15   100     08:00  08:01
2         15   100     08:00  08:05
2         15   101     08:10  08:15
2         15   102     08:20  08:25
2         15   103     08:30  08:33
我想这只是开始的一部分,我真正想要的是:
position price
1         15 
2         60
因此,我需要了解每个职位的总付款。
但是现在,我需要的是:对于每个位置和 orderid,我只想要具有最高 otherlog 条目的行。
现在还有其他日志时间低于购买日志时间,但我将它们过滤掉了buylog < otherlog。
但是现在我不知道如何仅显示每个 orderid-group 中最高的 otherlog。我试过了max(otherlog),但它仍然输出第一个表。
这是将三个表连接在一起后的视图,我想在同一个查询中获得预期的结果。
查询是这样的:
select position,price,orderid,buylog,otherlog 
from table1 inner join table2 on t1.userid=t2.userid  
inner join table3 on t2.id=t2.id 
where (some conditions to narrow down the results)
我正在使用 ms sql server 2012。
//编辑
查询:
Use [dbname]
go
    with cte
    as  (   select olt.position,
                ot.price,
                ot.orderid,
                ot.buylog = min(ot.buylog) over (partition by olt.position,ot.orderid),
                olt.otherlog = max(olt.otherlog) over (partition by olt.position,ot.orderid),
                rn=row_number() over(partition by olt.position, order by olt.position)
            from ordertable as ot inner join anothertable as at 
                            on ordertable.userid=anothertable.userid
                inner join otherlogtable as olt on anothertable.id=otherlogtable.sessionlogid
        )
    select  
    olt.position,
    ot.price,
    ot.orderid,
    ot.buylog,
    olt.otherlog
    from
    cte
    where
    rn=1