1

我正在尝试创建一个查询,允许我报告我们的客户是如何发现我们的(即通过谷歌、大喊、口口相传等)。

我有两张桌子:

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

但我不确定如何创建此报告。

4

1 回答 1

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;
于 2013-03-11T18:43:08.540 回答