我试图想出一种方法,我只能用最近的 ACCOUNT 获得 16 行(这是基于 SERV_ACCT 的 16 条不同的记录)。我正在使用 Distinct 和 group by,我认为这可以解决问题,但我一直得到 20 行。
宣布
@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