我正在尝试创建一个查询,让我能够报告客户如何发现我们(例如通过谷歌,大喊,口口相传等)。
我有两张桌子:
Customer
name
CreatedDate
SourceID
Sources
SourceID
SourceName
此查询:
SELECT Customer.CreatedDate, Source.SourceName
FROM Customer INNER JOIN
Source ON Customer.SourceID = Source.SourceID
给我一个按日期记录的所有来源列表:
2011-05-05 00:00:00:000 Word Of Mouth
2011-05-05 00:00:00:000 Word Of Mouth
2011-05-05 00:00:00:000 Word Of Mouth
2011-05-05 00:00:00:000 Walk In
2011-05-05 00:00:00:000 Yell.com
2011-05-05 00:00:00:000 Google Search
我想要的是一个列表,我可以导入饼图和报告:
January 2013
Word of Mouth: 15
Walk In: 5
Google Search: 6
Yell.com 5
February 2013
Word of Mouth: 11
Walk In: 0
Google Search: 8
Yell.com 3
但我不确定如何创建此报告。
答案 0 :(得分:4)
SELECT [Month] = DATEADD(MONTH, DATEDIFF(MONTH, 0, c.CreatedDate), 0),
s.SourceName,
c = COUNT(*)
FROM dbo.Customer AS c
INNER JOIN dbo.Source AS s
ON c.SourceID = s.SourceID
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, c.CreatedDate), 0),
s.SourceName
ORDER BY [Month], s.SourceName;
如果您只想要一个特定的月份,那么:
SELECT s.SourceName, c = COUNT(*)
FROM dbo.Customer AS c
INNER JOIN dbo.Source AS s
ON c.SourceID = s.SourceID
WHERE c.CreatedDate >= '20130101'
AND c.CreatedDate < '20130201'
GROUP BY s.SourceName
ORDER BY s.SourceName;