我是SQL的新手......
我正在使用以下三个表:
表:广告系列
Campaign SourcePhone StartDate EndDate
A 1112223333 20140303 20140309
B 2223334444 20140303 20140309
C 1112223333 20140310 20140316
D 3334445555 20140217 20150217
表:PhoneMapping(将SourcePhone从广告系列映射到订单表)
SourcePhone TransferToPhone
1112223333 9998887777
1112223333 8887776666
2223334444 7776665555
3334445555 6665554444
3334445555 5554443333
表:订单
Date TransferToPhone Orders
20140304 9998887777 3
20140304 8887776666 4
20140304 6665554444 34
20140305 7776665555 7
20140305 9998887777 5
20140306 9998887777 10
20140306 8887776666 13
20140307 8887776666 7
20140309 7776665555 1
20140311 9998887777 35
20140313 8887776666 8
20140315 9998887777 22
20140305 6665554444 11
我一直在尝试提出一个将连接这三个表并提供以下结果的查询。基本上,我需要为每个广告系列,SourcePhone#,转移到电话号码和日期范围(每个广告系列的StartDate和EndDate之间)提供一笔TotalOrders。以下是我期待查询提供的结果(我认为我做了正确的数学运算)。非常感谢任何帮助!
预期结果:
Campaign SourcePhone TransferToPhone StartDate EndDate TotalOrders
A 1112223333 9998887777 20140303 20140309 18
A 1112223333 8887776666 20140303 20140309 24
B 2223334444 7776665555 20140303 20140309 8
C 1112223333 9998887777 20140310 20140316 57
C 1112223333 8887776666 20140310 20140316 8
D 3334445555 6665554444 20140217 20150217 45
以下是我尝试过的内容,但不会根据日期范围对数据进行分组:
SELECT C.Campaign, C.SourcePhone, PM.TransferToPhone, C.StartDate , C.EndDate, O.TotalOrders
FROM Campaigns AS C
INNER JOIN
(SELECT SourcePhone, TransferToPhone
FROM PhoneMapping
WHERE (TransferToPhone IS NOT NULL)) AS PM ON C.SourcePhone = PM.SourcePhone
INNER JOIN
(SELECT TransferToPhone, SUM(Orders) AS TotalOrders
FROM Orders
WHERE (Orders IS NOT NULL)
Group by TransferToPhone) AS O ON PM.TransferToPhone = O.TransferToPhone
GROUP BY C.Campaign, C.SourcePhone, PM.TransferToPhone, C.StartDate , C.EndDate
答案 0 :(得分:1)
这能满足您的需求吗?
SELECT C.Campaign,
C.SourcePhone,
P.TransferToPhone,
C.StartDate,
C.EndDate,
SUM(O.TotalOrders)
FROM Campaigns C
JOIN PhoneMapping P
ON C.SourcePhone = P.SourcePhone
JOIN Orders O
ON O.TransferToPhone = P.TransferToPhone
GROUP BY C.Campaign, C.StartDate, C.EndDate, P.SourcePhone, P.TransferToPhone