我有一个包含5列Emp
,Surname
,CSD
,Term Rsn
和Date
的表格。前4列将保持不变,但日期将更改,例如。一个拥有30个不同日期的Emp可以有30条记录。
这是我的代码,但是当我将[Date]添加到select时它会返回所有30条记录,而我正在尝试返回一条带有最后日期的记录
Create PROCEDURE testPro(
@reportStartDate date,
@reportEndDate date
)
AS
BEGIN
SELECT DISTINCT Emp, Surname, CSD, CASE WHEN CSD<= @reportStartDate
THEN
CASE WHEN [Term Rsn] != 0 THEN
CASE WHEN [Date] <= @reportEndDate THEN
(DATEDIFF(dd,@reportStartDate, [Date]) - (2*
DATEDIFF(wk,@reportStartDate,[Date])))+1 ELSE (DATEDIFF(dd,@reportStartDate, @reportEndDate) - (2*
DATEDIFF(wk,@reportStartDate,@reportEndDate)))+1 END ELSE (DATEDIFF(dd,@reportStartDate, @reportEndDate) - (2*
DATEDIFF(wk,@reportStartDate,@reportEndDate)))+1 END
ELSE
CASE WHEN [Term Rsn] != 0 THEN
CASE WHEN [Date] <= @reportEndDate THEN
(DATEDIFF(dd,CSD, [Date]) - (2*
DATEDIFF(wk,CSD,[Date])))+1 ELSE (DATEDIFF(dd,CSD, @reportEndDate) - (2*
DATEDIFF(wk,CSD,@reportEndDate)))+1 END ELSE (DATEDIFF(dd,CSD, @reportEndDate) - (2*
DATEDIFF(wk,CSD,@reportEndDate)))+1 END
END AS [Working Days]
FROM GyPremiumsTemp
WHERE CSD < @reportEndDate AND [Date] > @reportStartDate --AND [Date] = (select max([Date]) FROM GyPremiumsTemp)
ORDER BY Emp ASC
END
EXEC testPro '2012-01-01', '2012-12-31'
答案 0 :(得分:1)
选择日期字段时使用: 选择最大(日期),Emp,姓氏 从表 Emp,姓氏小组
This will give you one record per employee.I hope this helps.
答案 1 :(得分:0)
写如下:
Create PROCEDURE testPro(
@reportStartDate date,
@reportEndDate date
)
AS
BEGIN
select Emp, Surname, CSD,[Working Days] , Max(Date) as [Date]
From (
SELECT DISTINCT Emp, Surname, CSD, CASE WHEN CSD<= @reportStartDate
THEN
CASE WHEN [Term Rsn] != 0 THEN
CASE WHEN [Date] <= @reportEndDate THEN
(DATEDIFF(dd,@reportStartDate, [Date]) - (2*
DATEDIFF(wk,@reportStartDate,[Date])))+1
ELSE (DATEDIFF(dd,@reportStartDate, @reportEndDate) - (2*
DATEDIFF(wk,@reportStartDate,@reportEndDate)))+1 END
ELSE (DATEDIFF(dd,@reportStartDate, @reportEndDate) - (2*
DATEDIFF(wk,@reportStartDate,@reportEndDate)))+1 END
ELSE
CASE WHEN [Term Rsn] != 0 THEN
CASE WHEN [Date] <= @reportEndDate THEN
(DATEDIFF(dd,CSD, [Date]) - (2*
DATEDIFF(wk,CSD,[Date])))+1
ELSE (DATEDIFF(dd,CSD, @reportEndDate) - (2*
DATEDIFF(wk,CSD,@reportEndDate)))+1 END
ELSE (DATEDIFF(dd,CSD, @reportEndDate) - (2*
DATEDIFF(wk,CSD,@reportEndDate)))+1 END
END AS [Working Days],[Date] -- Add all Dates here
FROM GyPremiumsTemp
WHERE CSD < @reportEndDate AND [Date] > @reportStartDate
) T
Group By Emp, Surname, CSD,[Working Days]
ORDER BY Emp ASC
END
EXEC testPro '2012-01-01', '2012-12-31'
在这里查看Demo。