1

我的第一个问题长期潜伏在这里。

我有以下表格:

  • 账户
  • 电子邮件
  • 电话号码

我想从 Accounts 中获取所有内容,并且对于每个 Accounts 记录,从其中 Accounts.ID = Emails.AcctID 或 Accounts.ID = PhoneNumbers.AcctID 的电子邮件和电话号码中获取最新的 Top 1。

我的 RS 目前是: SELECT ACCT.* FROM Accounts AS ACCT OUTER APPLY (SELECT TOP 1 E.* FROM Emails AS E WHERE E.E_AcctID = ACCT.ACCT_ID ORDER BY E.E_ID DESC) EM OUTER APPLY (SELECT TOP 1 PH. * FROM PhoneNumbers AS PH WHERE PH.PH_AcctID = ACCT.ACCT_ID ORDER BY PH_ID DESC) PH WHERE ACCT.ACCT_Status > 2;

问题是并非每个帐户在电子邮件或电话号码中都有相应的记录。

所以,一些 APPLY RS 是空的,然后我得到这个 RS 错误: ADODB.Recordset error '800a0cc1' 在与请求的名称或序号相对应的集合中找不到项目。

知道如何解决空记录集吗?

提前谢谢了。干杯,诺亚

4

2 回答 2

0

假设您在每个表中都有一个 created_datetime 列来指定最近的行,我们可以使用 RowNumber 函数来完成这项工作,请参见此示例

declare @ACCOUNTS table (ID_ACC int)
declare @EMAILS table (EMAIL VARCHAR(50), ID_ACC int, CREATED_DATETIME DATETIME)
declare @PHONES table (PHONE VARCHAR(50), ID_ACC int, CREATED_DATETIME DATETIME)


insert into @ACCOUNTS
SELECT '1' ID_ACC
UNION ALL 
SELECT '2' ID_ACC
UNION ALL 
SELECT '3' ID_ACC

INSERT INTO @EMAILS
SELECT 'MyEmail@test.com' EMAIL,'1' ID_ACC, '2015-12-14 22:00:00' CREATED_DATETIME
UNION ALL 
SELECT 'MyNewemail@test.com' EMAIL,'1' ID_ACC, '2015-12-14 22:53:00'
UNION ALL 
SELECT '3rdemail@test.com' EMAIL,'3' ID_ACC, '2015-12-14 22:54:00'
UNION ALL 
SELECT 'NEW3rdemail@test.com' EMAIL,'3' ID_ACC, '2015-12-14 22:55:30'


INSERT INTO @PHONES
SELECT '00213555555' PHONE,'1' ID_ACC, '2015-12-14 22:10:00' CREATED_DATETIME
UNION ALL 
SELECT '00213554444' PHONES,'2' ID_ACC, '2015-12-14 22:54:00'
UNION ALL 
SELECT '00213556666' PHONES,'3' ID_ACC, '2015-12-14 22:54:00'
UNION ALL 
SELECT '00213557777' PHONES,'3' ID_ACC, '2015-12-14 23:10:00'

 SELECT 
 *
 FROM
 (SELECT 
 ROW_NUMBER () over (partition by A.ID_ACC order by E.CREATED_DATETIME DESC,P.CREATED_DATETIME DESC) AS ROW_ORDER,
 A.ID_ACC,
 E.EMAIL,
 P.PHONE
 FROM @ACCOUNTS as A
 left join @EMAILS as E
 on A.ID_ACC=E.ID_ACC
 left join @PHONES as P
 on A.ID_ACC=P.ID_ACC) AS TAB
 WHERE TAB.ROW_ORDER=1
于 2015-12-14T22:28:27.653 回答
0

问题解决了!!

我将 RS 开头的“ACCT.*”替换为“*”,就成功了。我无意中排除了其他表!

感谢所有观看和评论的人!

于 2015-12-14T21:58:22.633 回答