我需要计算一个团队成员在指定时间范围内工作的门票数量(基于月份)。我有以下代码,显示了整个时间段(从9月到3月)的门票数量。我应该如何修改代码以查看每月的票数。 这是我的代码,其中显示了带有实际日期的票证ID:
select distinct(t1.ticketid) as [Tickets],
t1.BuilderAnalystID,t2.EMPFullName from table1 as t1
inner join employee as t2
on t1.BuilderAnalystID=t2.EmployeeID
where
builderanalystid='7' and
StatusID <>'12'and
cast(BuildCMPLTDT as date)>= '2017-09-01'
and cast(BuildCMPLTDT as date)< '2018-04-01'
我可以将整个结果导出到Excel并创建一个数据透视表以实现我的目标,但只是想知道是否可以在sql中完成。
这就是我想要的:
基于Amrita Srivastava建议的查询的输出:
答案 0 :(得分:1)
这是基本查询...您可以根据需要添加删除列...
select count(ticketid), [MONTH] = datename(MM, BuildCMPLTDT )
FROM table1
GROUP BY datename(MM, BuildCMPLTDT )
已更新(具有特定时间范围):
select count(DISTINCT ticketid), [MONTH] = datename(MM, BuildCMPLTDT )
FROM table1
WHERE CONVERT(DATE,compl_date) BETWEEN CONVERT(DATE,'2017-09-01') AND CONVERT(DATE,'2018-04-01')
GROUP BY datename(MM, BuildCMPLTDT )
答案 1 :(得分:0)
适合您的查询,您将使用:
select t2.EMPFullName, year(BuildCMPLTDT), month(BuildCMPLTDT),
count(*) as num_tickets
from table1 t1 join
employee t2
on t1.BuilderAnalystID = t2.EmployeeID
where builderanalystid = 7 and -- looks like a number so removed single quotes
StatusID <> 12 and -- looks like a number so removed single quotes
BuildCMPLTDT >= '2017-09-01' and -- `cast()` is unnecessary
BuildCMPLTDT < '2018-04-01'
group by t1.BuilderAnalystID, t2.EMPFullName, year(BuildCMPLTDT), month(BuildCMPLTDT);
拉月份时,也应该拉年份。