Предположим, у меня есть таблица:
Table A
Period Name| Type Name| Date | Quantity
-----------------------------
Yearly | General | 2019-09-01 | 24
Yearly | General | 2019-11-01 | 30
Yearly | Casual | 2019-09-01 | 6
Я хочу получить все группы строк по PeriodName, TypeName, но по макс. Дате.
У меня есть группа по макс. Дате, затем присоединиться к orginalтаблица для получения результата:
SELECT dbo.tbl_WPT_LeaveType.TypeName, dbo.tbl_WPT_EmployeeLeavePolicy.FK_tbl_WPT_LeaveType_ID, dbo.tbl_WPT_LeavePeriod.PeriodName,
dbo.tbl_WPT_EmployeeLeavePolicy.FK_tbl_WPT_LeavePeriod_ID, dbo.tbl_WPT_EmployeeLeavePolicy.Leave, dbo.tbl_WPT_EmployeeLeavePolicy.WithOutRequest,
dbo.tbl_WPT_EmployeeLeavePolicy.ApplyFrom
FROM dbo.tbl_WPT_EmployeeLeavePolicy INNER JOIN
dbo.tbl_WPT_LeaveType ON dbo.tbl_WPT_EmployeeLeavePolicy.FK_tbl_WPT_LeaveType_ID = dbo.tbl_WPT_LeaveType.ID INNER JOIN
dbo.tbl_WPT_LeavePeriod ON dbo.tbl_WPT_EmployeeLeavePolicy.FK_tbl_WPT_LeavePeriod_ID = dbo.tbl_WPT_LeavePeriod.ID INNER JOIN
---------same table to get max date
(SELECT TOP (100) PERCENT MAX(tbl_WPT_EmployeeLeavePolicy_1.ApplyFrom) AS ApplyFrom, tbl_WPT_EmployeeLeavePolicy_1.FK_tbl_WPT_LeaveType_ID,
tbl_WPT_EmployeeLeavePolicy_1.FK_tbl_WPT_LeavePeriod_ID
FROM dbo.tbl_WPT_EmployeeLeavePolicy AS tbl_WPT_EmployeeLeavePolicy_1 INNER JOIN
dbo.tbl_WPT_LeaveType AS tbl_WPT_LeaveType_1 ON tbl_WPT_EmployeeLeavePolicy_1.FK_tbl_WPT_LeaveType_ID = tbl_WPT_LeaveType_1.ID INNER JOIN
dbo.tbl_WPT_LeavePeriod AS tbl_WPT_LeavePeriod_1 ON tbl_WPT_EmployeeLeavePolicy_1.FK_tbl_WPT_LeavePeriod_ID = tbl_WPT_LeavePeriod_1.ID
WHERE (tbl_WPT_EmployeeLeavePolicy_1.FK_tbl_WPT_Employee_ID = @EmpID) AND (tbl_WPT_EmployeeLeavePolicy_1.FK_tbl_WPT_LeavePeriod_ID = 2) AND
(tbl_WPT_EmployeeLeavePolicy_1.ApplyFrom <= @MonthFrom)
GROUP BY tbl_WPT_EmployeeLeavePolicy_1.FK_tbl_WPT_LeaveType_ID, tbl_WPT_EmployeeLeavePolicy_1.FK_tbl_WPT_LeavePeriod_ID) AS x ON x.FK_tbl_WPT_LeaveType_ID = dbo.tbl_WPT_EmployeeLeavePolicy.FK_tbl_WPT_LeaveType_ID AND x.FK_tbl_WPT_LeavePeriod_ID = dbo.tbl_WPT_EmployeeLeavePolicy.FK_tbl_WPT_LeavePeriod_ID AND x.ApplyFrom = dbo.tbl_WPT_EmployeeLeavePolicy.ApplyFrom
WHERE (dbo.tbl_WPT_EmployeeLeavePolicy.FK_tbl_WPT_Employee_ID = @EmpID) AND (dbo.tbl_WPT_EmployeeLeavePolicy.FK_tbl_WPT_LeavePeriod_ID = 2) AND
(dbo.tbl_WPT_EmployeeLeavePolicy.ApplyFrom <= @MonthFrom)
Period Name| Type Name| Date | Quantity
-----------------------------------------------
Yearly | General | 2019-11-01 | 30
Yearly | Casual | 2019-09-01 | 6