这是问题:
使用以下注册创建表
Member Enrl_Start_Date Enrl_End_Date
M1 1-1-2017 11-20-2017
M1 12-31-2017 02-01-2018
M1 02-15-2018 04-30-2018
M1 06-10-2018 12-31-2018
M2 1-1-2017 11-20-2017
M2 12-31-2017 02-01-2018
M3 02-15-2018 04-30-2018
M3 06-10-2018 12-31-2018
M4 1-1-2017 11-20-2017
M4 12-31-2017 02-01-2018
M5 02-15-2018 04-30-2018
M5 06-10-2018 12-31-2018
我创建了一个示例表,如下所示:
CREATE TABLE [dbo].[Enrollments](
[Member] [varchar](50) NULL,
[Enrl_Start_Date] [date] NULL,
[Enrl_End_Date] [date] NULL
);
然后,我将提供的值插入dbo.Enrollments。
做完在线研究之后,我能够在下面的查询中写东西。它们对我来说似乎很好,但是我仍然不确定我是否以正确的方式前进。有什么建议吗?这将是真正的帮助!
select Member, count(*) as TotalEnrollments
from [dbo].[Enrollments]
where year([Enrl_Start_Date])=2018
group by Member
输出:
Member TotalEnrollments
M1 2
M3 2
M5 2
select [Member],datediff(day,[Enrl_Start_Date],[Enrl_End_Date]) as TotalEnrolledDays
from [dbo].[Enrollments]
where year(enrl_start_date)=2018
输出:
Member TotalEnrolledDays
M1 74
M1 204
M3 74
M3 204
M5 74
M5 204
select count(*) as TotalEnrolledMembers
from [dbo].[Enrollments]
where [Enrl_Start_Date]= '2018-12-31'
输出:
TotalEnrolledMembers
0
答案 0 :(得分:0)
您的查询部分正确。
您无需根据[dbo].[Enrollments].Members
对查询进行分组。您可以简单地将结果返回为
SELECT COUNT(1) AS 'Number of Members enrolled in 2018'
FROM [dbo].[Enrollments]
WHERE year([Enrl_Start_Date])=2018
SELECT [Member],
DATEDIFF(day,
CASE
WHEN YEAR(Enrl_Start_Date) < 2018
THEN '2018-01-01'
ELSE Enrl_Start_Date
END,
CASE
WHEN YEAR([Enrl_End_Date]) > 2018
THEN '2018-12-31'
ELSE [Enrl_End_Date]
END) AS TotalEnrolledDays
FROM [dbo].[Enrollments]
WHERE YEAR(enrl_start_date) = 2018
OR YEAR(Enrl_End_Date) = 2018;
您的成员从2017年12月31日至2018年2月1日注册。您最初具有的查询将忽略这些成员(即使他们已在2018年注册)。因此,您也必须考虑那些成员。
年份的情况(Enrl_Start_Date)<2018 THEN'2018-01-01'ELSE Enrl_Start_Date END,
-如果他们的注册于2017年开始(并于2018年结束),则开始日期应为01/01/2018,因为您不想计算2017年的天数
案例 年份([Enrl_End_Date])> 2018 则'2018-12-31' ELSE [Enrl_End_Date]
-如果他们的入学时间(从2018年开始)在2019年结束,则您不希望计算从2019年开始的日子。因此,您的结束日期将是31/12/2018
Select Count(*)
,只需Select Count(1)
就足够了