MS SQL问题:Max和GUID

时间:2011-05-26 09:10:45

标签: sql-server tsql

select  first(orderid), accountid 
from [Order] 
group by AccountId 
order by DateCreated desc

first()是无效的功能。

max()不适用于唯一标识符

我如何获得为所有帐户创建的最后一个orderid?感谢。

3 个答案:

答案 0 :(得分:1)

像(未经测试)的东西:

;WITH CTE_LatestOrders AS (
    select accountid, lastcreated = max(datecreated)
    from [Order]
    group by accountid
)
select
    accountid, orderid
from
    [Orders] o
    join CTE_LatestOrders l 
        on o.AccountID = l.AccountID 
        and o.datecreated = l.lastcreated

答案 1 :(得分:0)

您也可以在下面继续。

Select Temp.orderid, T.AccountId, T.DateCreated
From
(
    Select AccountId, max(DateCreated) as  DateCreated
    From [Order]
    Group By AccountId
)T
Inner Join [Order] Temp on Temp.AccountId = T.AccountId 
AND Temp.DateCreated = T.DateCreated

CTE不是UDT / temp表;将CTE视为仅针对当前查询定义的视图。就像一个视图一样,CTE被扩展并折叠成整体查询计划。全局优化仍将发生,但不要仅仅因为您使用CTE而只考虑执行一次查询。这是一个适合这个空间的简单示例:WITH vw AS(SELECT COUNT(*)c FROM Person)SELECT a.c,b.c FROM vw a,vw b;查询计划将清楚地显示两个扫描/聚合和连接,而不是仅两次投射相同的结果。

答案 2 :(得分:0)

Max()适用于MS SQL 2012中的唯一标识符