2014-02-13 48 views
-4
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

在上面的查詢中沒有字段名稱,例如min_record_date,max_record_date? – Zeeshan

+0

我說我有這樣的數據。 –

回答

1
SELECT id, MIN(record_date), MAX(record_date) FROM table GROUP BY id 
+0

我需要日期過濾器。這意味着我需要記錄介於今天的日期和未來的30天之間。 –

+0

我回答了你的問題。如果這個答案不適合你的需求,你應該重新考慮你的問題。 – Alexander

+0

上面編輯.... –

1
SELECT id, 
     MIN(record_date) AS min_record_date, 
     MAN(record_date) AS max_record_date 
    FROM table 
GROUP BY id; 
+0

我需要在日期過濾器。這意味着我需要記錄介於今天的日期和未來的30天之間。 –

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) 
+0

它表示日曆日在條款 –

+0

中無效,它顯示錯誤:「日曆日期」在HAVING子句中無效,因爲它不包含在聚合函數或GROUP BY子句中。 –

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