2016-06-10 52 views
0

我想按分支和年份統計項目。 我試過這段代碼,但不起作用。任何幫助表示讚賞。如何按分支和年度sql服務器計數記錄

SELECT  COUNT(ProjectIndentID) AS NoOfProjects, BranchID, DATEPART(year, PIDate) AS Expr1 
FROM   dbo.ProjectIndent 
GROUP BY BranchID, PIDate 
HAVING  (DATEPART(year, PIDate) = '2016') 

回答

1

您需要group by年,沒有日期:

SELECT COUNT(ProjectIndentID) AS NoOfProjects, BranchID, 
     DATEPART(year, PIDate) AS yr 
FROM dbo.ProjectIndent 
WHERE DATEPART(year, PIDate) = 2016 
GROUP BY BranchId, DATEPART(year, PIDate) ; 

另外:

  • having邏輯確實應該在where條款。最好在聚合之前過濾數據,而不是後綴。
  • DATEPART()返回一個整數,所以使用2016而不是'2016'
  • 您可能想要一個ORDER BY
  • WHERE子句應該是`WHERE PIDate> ='2016-01-01'AND PIDate <'2017-01-01'。這允許索引用於過濾(如果適用)。