我有这个查询,它给出了这个结果:
DECLARE
@CustomerID int = 8,
@UtilityCompanyID int = 1
SELECT MD.SERV_ACCT, AD.ACCOUNT, MD.SERV_ADDRESS
FROM
(SELECT DISTINCT SERV_ACCT, SERV_ADDRESS, MAX(INV_DATE) as MAXINVDATE
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, SERV_ADDRESS) MD
join tblAPSdata AD on MD.SERV_ACCT = AD.SERV_ACCT
and MD.MAXINVDATE = AD.INV_DATE
结果:
SERV_ACCT ACCOUNT SERV_ADDRESS
0289S61288 117512280 5250 E MONTGOMERY RD
1435S01282 117512280 5801 E SEVEN PALMS LN
2498S21288 117512280 27880 N 64 ST
5538S21284 117512280 5802 E DOVE VALLEY RD
6109S12286 117512280 5405 E PINNACLE VISTA DR
7488S22289 117512280 5555 E PINNACLE VISTA DR
8058S12287 117512280 5405 E PINNACLE VISTA DR
9058S00288 117512280 33606 N 60 ST
9645S21281 117512280 4322 E DESERT WILLOW PKWY
1440S13289 312937281 2610 N WEST ST
5384S92284 979437282 1701 E PONDEROSA PKWY
0492S90281 117512280 33424 N 60 ST
1303S90280 117512280 33401 N 56 ST
1548S00286 117512280 33606 N 60 ST
7358S00281 117512280 33606 N 60 ST
9168S00282 117512280 33016 N 60 ST
我想创建一个新列,如下所示:
SERV_ACCT ACCOUNT SERV_ADDRESS
0289S61288 117512280 4324E MONT 0289S61288, 117512280, 4324E MONT
1435S01282 117512280 432E SE 1435S01282, 117512280, 432E SE
2498S21288 117512280 reN 64 ST 2498S21288, 117512280, reN 64 ST
5538S21284 117512280 reE DOV 5538S21284, 117512280, reE DOV
其余的以此类推。基本上最后一列将是 SERV_ACCT、ACCOUNT、SERV_ADDRESS,但我不知道该怎么做。