我设计了一个以下的sql查询来获取12月份完成的访问总数。
select q.MonthName, count(q.MonthName) as TotalVisit from
(
SELECT DATENAME( MONTH,v.VisitDate) as MonthName
FROM Visits v
INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID
WHERE a.ClientID IN (33,67)
AND v.VisitDate BETWEEN '01/12/2013' AND '31/12/2013'
)q
group by q.MonthName
结果:
MonthName TotalVisit
December 164
我可以通过在SQL SEVER 2008中编写单个查询而不使用内部查询来获得相同的结果吗?
答案 0 :(得分:0)
SELECT DATENAME( MONTH,v.VisitDate) as MonthName,
COUNT(*) AS TotalVisit
FROM Visits v
INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID
WHERE a.ClientID IN (33,67)
AND v.VisitDate BETWEEN '01/12/2013' AND '31/12/2013'
GROUP BY DATENAME( MONTH,v.VisitDate)
答案 1 :(得分:0)
在我看来,外部查询是不必要的。这应该给出相同的结果:
SELECT DATENAME(MONTH,v.VisitDate) as MonthName, count(*) as TotalVisit
FROM Visits v
INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID
WHERE a.ClientID IN (33,67)
AND v.VisitDate BETWEEN '01/12/2013' AND '31/12/2013'
group by DATENAME(MONTH,v.VisitDate)
它的工作原理是因为你的“count()”函数实际上只是计算记录。因此count(*)和count(MonthName)之间没有区别。
答案 2 :(得分:0)
你基本上已经在你的内部查询中完成了它。只是一些变化:
SELECT DATENAME(MONTH,v.VisitDate) as MonthName
,COUNT(v.ID) AS Visits
FROM Visits v
INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID
WHERE a.ClientID IN (33,67)
AND (v.VisitDate >= '01/12/2013' AND v.VisitDate <= '31/12/2013') --changed this for performance
GROUP BY DATENAME(MONTH,v.VisitDate)