----------------------------------------------------------
Emp Id Pgm_Start Date End Date Total_No_of_Days
----------------------------------------------------------
- ID001 11/04/2103 11/10/2013 7
- ID001 10/05/2013 10/08/2013 4
- ID002 10/09/2013 10/15/2013 7
- ID002 09/02/2013 09/06/2013 5
我的以下查询提供以下内容:
SELECT EmpID,COUNT(ProgramID) AS Total_Programs,
SUM(CAST(Total_No_Of_Days AS INT)) AS Total_Program_Days from table1
GROUP BY empid ORDER BY Total_Programs desc,Total_Program_Days desc
--------------------------------------------------------------------------
Emp Id Total_Program Total_Program_Days Days_since_last_Program
-------------------------------------------------------------------------
- ID001 2 11 ---need this value---
- ID002 2 12 ---need this value----
我想基于table1为每个员工计算最后一个字段(Days_since_last_Program)..
所以我锻炼......
此查询为“ID001”
提供最后一个程序End_date SELECT * from table1 where End_Date= (select
MAX(Convert(Date,End_Date)) from table1 where EmpId=’ID001’) and
EmpID=ID001
所以,最后获得价值但是我为单个用户提供了这个:
SELECT ABS( DATEDIFF(DAY,CURRENT_TIMESTAMP,
(SELECT End_date from table1 where
End_Date = (select MAX(Convert(Date,End_Date))
FROM table1 where EmpId=ID001) and
EmpID=ID001))) as "Days_since_last_Program"
我希望所有员工的这个计算值为“自上次计划以来的天数”列,但无法弄清楚如何,请帮我弄清楚.. 提前谢谢..
答案 0 :(得分:0)
它不仅仅是......
SELECT
EmpID,
COUNT(ProgramID) AS Total_Programs,
SUM(CAST(Total_No_Of_Days AS INT)) AS Total_Program_Days,
DATEDIFF(DAY, MAX(CONVERT(DATE,End_Date)), GETDATE()) AS Days_Since_Last_Program
FROM table1
GROUP BY empid
ORDER BY Total_Programs DESC,Total_Program_Days DESC
答案 1 :(得分:0)
在你的查询中发布了很少的修改..
SELECT *
FROM table1 t1
WHERE end_date = (SELECT MAX(convert(DATE, t2.end_date))
FROM table1 t2
WHERE t2.empid = t1.empid)
只需要让一个用户认为end_date没有重复。 否则你可能会为同一个用户获得多行。
答案 2 :(得分:0)
这将使用相关子查询:
SELECT
*,
ABS(DATEDIFF(DAY,CURRENT_TIMESTAMP,(
SELECT MAX(Convert(Date,t2.End_Date))
from table1 t2
where t2.EmpId=t1.EmpId
))) AS [Days_since_last_Program]
FROM table1 t1;