2

编辑:我正在使用 SQL Server

我环顾四周寻找一个例子,但找不到任何东西,所以我将开始一个新线程......

我有 3 张桌子。

帐户

  • 帐户ID

帐户注册

  • AccountEnrollID
  • 帐户ID
  • 帐户类型 ID
  • 注册日期

帐户类型

  • 帐户类型 ID
  • 帐户类型

AccountEnroll 表是一个桥接表,用于跟踪每个客户的注册历史。我想使用“EnrollDate”列来确定每个客户的当前帐户类型。我需要编写一个可以显示 AccountID、FirstName、LastName、(current)AccountType 的 SELECT 语句。

我无法让我的结果集显示每个客户的 MAX(EnrollDate) 记录。

4

3 回答 3

4

您可以使用公用表表达式非常简单地做到这一点。

with cte as (

select A.FirstName, A.LastName, AT.AccountType, AE.EnrollDate, row_number() over (partition by AE.AccountID order by EnrollDate desc) as [rn]
from Account as A
inner join AccountEnrolled as AE
   on A.AccountId = AE.AccountId
inner join AccountType as AT
   on AE.AccountTypeId = AT.AccountTypeId

)
select FirstName, LastName, AccountType, EnrollDate
from cte
where rn = 1
于 2012-10-07T16:16:31.047 回答
2

尝试这个:

SELECT 
  a.AccountID, a.FirstName, a.LastName, 
  at.AccountType AS 'Current AccountType'
FROM Account a
INNER JOIN
(
   SELECT AccountID, MAX(EnrollDate) MaxDate
   FROM AccountEnroll
   GROUP BY AccountID
) t
INNER JOIN AccountEnroll ae ON  ae.AccountID = t.AccountID 
                            AND ae.EnrollDate = t.MaxDate
INNER JOIN AccountType at ON ae.AccountTypeID = at.AccountTypeID
于 2012-10-07T15:45:21.210 回答
0

您可以使用相关的子查询:

SELECT A.AccountId, A.FirstName, A.LastName, AT.AccountType
FROM Account A
JOIN AccountEnroll AE
    ON A.AccountId = AE.AccountId
JOIN AccountType AT
    ON AE.AccountTypeId = AT.AccountTypeId
WHERE NOT EXISTS (
    SELECT 1
    FROM AccountEnroll
    WHERE AccountId = AE.AccountId
        AND EnrollDate > AE.EnrollDate
) 
于 2012-10-07T17:11:50.310 回答