我有一个复杂的问题。这个想法是,我需要一个表中不同的 Serv_Acct (这很容易,我已经有了):
DECLARE
@CustomerID int = 8,
@UtilityCompanyID int = 1
SELECT DISTINCT SERV_ACCT, MAX(INV_DATE)
FROM tblAPSData
WHERE SERV_ACCT NOT IN (SELECT ServiceAccount
FROM tblMEP_Meters
JOIN tblMEP_Sites
ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
JOIN tblMEP_Projects
ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
WHERE CustomerID = 8
AND Type = 1
)
AND ACCOUNT IN (SELECT AccountNumber
FROM tblMEP_CustomerAccounts
WHERE CustomerID = @CustomerID
AND UtilityCompanyID = @UtilityCompanyID)
AND INV_DATE > DATEADD(month, -6, getdate())
GROUP BY SERV_ACCT
当我运行它时,我得到 16 行:
SERV_ACCT (No column name)
0289S61288 2013-06-12 00:00:00.000
0492S90281 2013-06-12 00:00:00.000
1303S90280 2013-06-12 00:00:00.000
1435S01282 2013-06-12 00:00:00.000
1440S13289 2013-06-24 00:00:00.000
1548S00286 2013-06-12 00:00:00.000
2498S21288 2013-06-12 00:00:00.000
5384S92284 2013-06-24 00:00:00.000
5538S21284 2013-06-12 00:00:00.000
6109S12286 2013-06-12 00:00:00.000
7358S00281 2013-06-12 00:00:00.000
7488S22289 2013-06-12 00:00:00.000
8058S12287 2013-06-12 00:00:00.000
9058S00288 2013-06-12 00:00:00.000
9168S00282 2013-06-12 00:00:00.000
9645S21281 2013-06-12 00:00:00.000
现在,我没有得到的部分是,每个服务帐户都有一个帐号,有些服务帐户有多个帐号,我只想要一个具有最新日期的帐号的服务帐户。当我尝试这样做时看到问题:
DECLARE
@CustomerID int = 8,
@UtilityCompanyID int = 1
SELECT DISTINCT SERV_ACCT, ACCOUNT, MAX(INV_DATE)
FROM tblAPSData
WHERE SERV_ACCT NOT IN (SELECT ServiceAccount
FROM tblMEP_Meters
JOIN tblMEP_Sites
ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
JOIN tblMEP_Projects
ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
WHERE CustomerID = 8
AND Type = 1
)
AND ACCOUNT IN (SELECT AccountNumber
FROM tblMEP_CustomerAccounts
WHERE CustomerID = @CustomerID
AND UtilityCompanyID = @UtilityCompanyID)
AND INV_DATE > DATEADD(month, -6, getdate())
GROUP BY SERV_ACCT, ACCOUNT
ORDER BY SERV_ACCT
现在结果如下:
SERV_ACCT ACCOUNT (No column name)
0289S61288 117512280 2013-06-12 00:00:00.000
0492S90281 117512280 2013-06-12 00:00:00.000
0492S90281 651412281 2013-04-08 00:00:00.000
1303S90280 117512280 2013-06-12 00:00:00.000
1435S01282 117512280 2013-06-12 00:00:00.000
1440S13289 312937281 2013-06-24 00:00:00.000
1548S00286 117512280 2013-06-12 00:00:00.000
1548S00286 308710287 2013-04-08 00:00:00.000
2498S21288 117512280 2013-06-12 00:00:00.000
5384S92284 979437282 2013-06-24 00:00:00.000
5538S21284 117512280 2013-06-12 00:00:00.000
6109S12286 117512280 2013-06-12 00:00:00.000
7358S00281 117512280 2013-06-12 00:00:00.000
7358S00281 659710281 2013-04-08 00:00:00.000
7488S22289 117512280 2013-06-12 00:00:00.000
8058S12287 117512280 2013-06-12 00:00:00.000
9058S00288 117512280 2013-06-12 00:00:00.000
9168S00282 117512280 2013-06-12 00:00:00.000
9168S00282 570810282 2013-04-08 00:00:00.000
9645S21281 117512280 2013-06-12 00:00:00.000
如您所见, Serv_Acct 不再是 Distinct 了!我的目标是仅使用最新帐户获得不同的 Serv_Acct(即 16)。关于如何做到这一点的任何帮助?我问了一个朋友,她告诉我,我可以用临时表来做到这一点!真的吗?