Declare @dCurrentDate Date = CONVERT (DATE, GETDATE())
Declare @dNextDate Date = DATEADD(month,1,CONVERT (DATE, GETDATE()))
我创建了一个包含10个员工ID并且名称为@tbl
的表然后我写了一个查询,以选择未来30天员工的最短和最长日期。
SELECT
c.fkEmployeeId as Employee,
e.FullName,c.calendarday
FROM
EmployeeCalendar c
JOIN Employee e
ON (e.pkEmployeeId=c.fkEmployeeId)
GROUP BY c.fkEmployeeId,
e.FullName,
c.calendarday
HAVING
c.CalendarDay BETWEEN @dCurrentDate AND @dNextDate
AND c.fkEmployeeId IN (
SELECT
EmployeeId
FROM
@tbl
)
我得到了结果
Id | Name | Date
76 Muhammad 2014-03-05
76 Muhammad 2014-03-12
594 Khan 2014-02-14
但我需要
Id | Name | min_date | max_date
76 muhammad 2014-03-05 2014-03-12
594 khan 2014-02-14 2014-02-14
我怎么能得到这个。
答案 0 :(得分:1)
SELECT id, MIN(record_date), MAX(record_date) FROM table GROUP BY id
答案 1 :(得分:1)
SELECT id,
MIN(record_date) AS min_record_date,
MAN(record_date) AS max_record_date
FROM table
GROUP BY id;
答案 2 :(得分:0)
尝试这个......
DECLARE @dCurrentDate DATE = CONVERT (DATE, GETDATE ())
DECLARE @dNextDate
DATE = DATEADD (MONTH, 1, CONVERT (DATE, GETDATE ()))
SELECT
c.fkEmployeeId AS Employee,
e.FullName, MIN(c.calendarday),MAX(c.calendarday)
FROM
EmployeeCalendar c
JOIN Employee e
ON (e.pkEmployeeId = c.fkEmployeeId)
GROUP BY c.fkEmployeeId
HAVING c.CalendarDay BETWEEN @dCurrentDate
AND @dNextDate
AND c.fkEmployeeId IN
(SELECT
EmployeeId
FROM
@tbl)
答案 3 :(得分:0)
试试这个。
SELECT id,Name
MIN(record_date) AS min_date,
MAN(record_date) AS max_date
FROM table
GROUP BY id,Name
ORDER BY id