select datepart(yyyy,hiredate) as Hire_Date_of_Year,jobTitle,count(jobTitle) as Number_Of_Title
from [AdventureWorks2012].[HumanResources].[Employee]
group by jobTitle,hiredate
having hiredate like '2004%'
order by jobtitle asc
我得到的输出就是这个
Hire_Date_of_Year jobTitle number_of_Count
2004 Buyer 1
2004 Buyer 1
2004 Buyer 1
2004 Buyer 1
2004 Buyer 1
2004 Buyer 1
2004 Buyer 1
2004 Janitor 1
2004 Janitor 1
2004 Janitor 1
2004 Janitor 1
我正在寻找的输出
Hire_Date_of_Year jobTitle number_of_Count
2004 Buyer 7
2004 Janitor 4
先谢谢。
答案 0 :(得分:1)
您不应该使用like
进行日期比较。这最适用于字符串。这是一种编写所需查询的方法:
select datepart(yyyy, hiredate) as Hire_Date_of_Year,
jobTitle, count(jobTitle) as Number_Of_Title
from [AdventureWorks2012].[HumanResources].[Employee]
where datepart(yyyy, hiredate) = 2004
group by jobTitle, datepart(yyyy, hiredate)
order by jobtitle asc;
如果您愿意,datepart(yyyy, hiredate)
中的year(hiredate)
(或group by
如果您愿意)是可选的。如果您不包含它,select
需要将年份放在聚合函数中,例如max(datepart(yyyy, hiredate))
。
为了提高效率,我将条件移到where
子句。您可以在聚合后进行比较(即在having
子句中)。但这意味着group by
在进行过滤之前的所有年份都在进行分组。
答案 1 :(得分:0)
您需要按年份分组,而不是完整日期
SELECT DatePart(yy, hiredate) As Hire_Date_of_Year
, jobTitle
, Count(jobTitle) As Number_Of_Title
FROM [AdventureWorks2012].[HumanResources].[Employee]
WHERE DatePart(yy, hiredate) = 2004
GROUP
BY DatePart(yy, hiredate)
, jobTitle
答案 2 :(得分:0)
分组应该是:
group by jobTitle,datepart(yyyy,hiredate)
答案 3 :(得分:0)
尝试这样的事情:
SELECT jobTitle, Hire_Date_of_Year,SUM(number_of_Count)
FROM emp
GROUP BY jobTitle, Hire_Date_of_Year