0

布局:我有一个订阅者数据库,其中包含一个表中的订阅者信息,所有这些都具有唯一的 AccountID。

我有多个历史数据库,每个数据库都有一个历史表,所有这些都与订阅者数据库中的 AccountID 相关。

我需要:我需要为订阅者数据中的每个 AccountID 在任何历史数据库中输入的最新历史记录列表。每个 AccountID 1 条记录。

我可以通过多次点击数据库来实现这一点,但可能有数百万条记录,这在我的脑海中并不好。我想一击完成。

帮助。我。谢谢。

这是我已经尝试过的东西,但它没有为每个 AccountID 提供一条记录...

SELECT 
MAIN.*, 
ISNULL(SubData.Name, '') AS [Name], 
ISNULL(SubData.AcctLineCode, '') AS AcctLineCode, 
ISNULL(LTRIM(RTRIM(SubData.AcctNum)), '') AS AcctNum 

FROM 
(
    SELECT AccountID, AlarmDate, AlarmCode FROM [History1113]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
    UNION 
    SELECT AccountID, AlarmDate, AlarmCode FROM [History1013]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
    UNION 
    SELECT AccountID, AlarmDate, AlarmCode FROM [History0913]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
) 
AS MAIN 

LEFT JOIN Subscriber..[Subscriber Data] AS SubData ON Main.AccountID = SubData.AccountID 

ORDER BY AccountID, AlarmDate DESC
4

2 回答 2

2

我会这样做作为一个观点。最大的问题是确保视图可以看到所有历史表(如果它们位于单独的数据库中)。您可能必须进入链接服务器

Create view historytable
as
select * from historytable1
union all 
select * from historytable2
union all
etc...

现在从历史表中查询,就好像它是一个包含所有行的表一样。

编辑:您添加的语句没有聚合,因此它没有过滤(或分组依据)到一条记录的方法。

对您的回复:

让我们将我的视图称为主视图,这样我就不必输入太多了。

Select account_id, max(alarm_date) as maxdate from main group by account_id

这个简单的选择带回最近的记录。内部加入它,使其充当过滤器。

select ...
from main
inner join (Select account_id, max(alarm_date) as maxdate from main group by account_id) maxdate
on main.account_id = maxdate.account_ID and maxdate.maxdate = main.alarm_date

将您的订阅者加入添加到底部并填写您需要的列

于 2013-11-13T21:50:05.697 回答
0

在你们几个人的帮助下,我能够弄清楚这一点。所以,谢谢大家。

这是我如何让它工作的代码片段。我仍然需要做一些加入来引入帐户信息,但这是困难的部分。

`

SELECT MAIN.AccountID, MAX(MAIN.AlarmDate) AS AlarmDate FROM
(
SELECT AccountID, MAX(AlarmDate) AS AlarmDate FROM [History1113]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
GROUP BY AccountID

UNION

SELECT AccountID, MAX(AlarmDate) AS AlarmDate FROM [History1013]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
GROUP BY AccountID

UNION

SELECT AccountID, MAX(AlarmDate) AS AlarmDate FROM [History0913]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
GROUP BY AccountID
)
AS MAIN

GROUP BY MAIN.AccountID

`

于 2013-11-13T22:20:22.000 回答