我有以下数据
SalId EmpId TakenSal TakenDate AvailSal CompId
13 68 1000 02-Jul-2015 14000 1021
14 68 100 02-Jul-2015 13900 1021
15 69 1000 02-Jul-2015 11000 1021
16 82 1000 06-Jul-2015 9000 1024
17 82 1000 06-Jul-2015 8000 1024
18 83 1000 06-Jul-2015 9000 1024
19 83 1000 06-Jul-2015 8000 1024
20 82 1000 06-Jul-2015 7000 1024
21 82 1000 06-Jul-2015 6000 1024
22 82 1000 06-Jul-2015 5000 1024
23 82 1000 06-Jul-2015 4000 1024
24 94 1000 09-Jul-2015 9000 1014
25 94 1000 09-Jul-2015 8000 1014
26 94 1000 09-Jul-2015 7000 1014
27 94 1000 09-Jul-2015 6000 1014
我要在其中选择那些记录' TakenDate'离今天最近
我尝试过如下但是反感错误
select *
from Employee_SalaryDetails
where Employee_SalaryDetails.TakenDate = max(TakenDate)
group by Employee_SalaryDetails.EmpId
having count(Employee_SalaryDetails.EmpId)>0
答案 0 :(得分:0)
我认为您正在寻找从今天开始的最近日期数据。
我已尝试过您的实际数据,
CREATE TABLE AbbasTable
(
SalId INT
,EmpId INT
,TakenSal INT
,TakenDate date
,AvailSal INT
,CompId INT
)
insert into AbbasTable values (13, 68, 1000 , '02-Jul-2015', 14000 , 1021)
insert into AbbasTable values (14, 68, 100 ,'02-Jul-2015', 13900, 1021)
insert into AbbasTable values (15,69 ,1000 ,'02-Jul-2015', 11000, 1021)
insert into AbbasTable values (16,82 ,1000 ,'06-Jul-2015', 9000 , 1024)
insert into AbbasTable values (17,82 ,1000 ,'06-Jul-2015', 8000 , 1024)
insert into AbbasTable values (18,83 ,1000 ,'06-Jul-2015', 9000 , 1024)
insert into AbbasTable values (19,83 ,1000 ,'06-Jul-2015', 8000 , 1024)
insert into AbbasTable values (20,82 ,1000 ,'06-Jul-2015', 7000 , 1024)
insert into AbbasTable values (21,82 ,1000 ,'06-Jul-2015', 6000 , 1024)
insert into AbbasTable values (22,82 ,1000 ,'06-Jul-2015', 5000 , 1024)
insert into AbbasTable values (23,82 ,1000 ,'06-Jul-2015', 4000 , 1024)
insert into AbbasTable values (24,94 ,1000 ,'09-Jul-2015', 9000 , 1014)
insert into AbbasTable values (25,94 ,1000 ,'09-Jul-2015', 8000 , 1014)
insert into AbbasTable values (26,94 ,1000 ,'09-Jul-2015', 7000 , 1014)
insert into AbbasTable values (27,94 ,1000 ,'09-Jul-2015', 6000 , 1014)
对于查询以下的输出用途,
WITH FianlTable
AS
(
SELECT AT.*
,ROW_NUMBER() OVER(PARTITION BY empid ORDER BY takendate DESC) AS RN
FROM AbbasTable AT
)
SELECT *
FROM FianlTable
WHERE RN = 1
ORDER BY
TakenDate DESC
答案 1 :(得分:0)
如果表格中没有未来日期,只需返回最近的行(即“最接近今天的那些记录'TakenDate'):
select *
from Employee_SalaryDetails
where TakenDate = (select max(TakenDate) from Employee_SalaryDetails)
答案 2 :(得分:0)
如果您想要距离最近但在下方,可以使用
select esd1.*
from Employee_SalaryDetails AS esd1
where
esd1.TakenDate <= getdate()
and not exists (select 1
from Employee_SalaryDetails AS esd2
where esd2.TakenDate <= getdate()
and esd2.TakenDate > esd1.TakenDate )