我正在使用MySQL DBMS并希望从表中选择最近年份的数据。 (不包括过去一年的数据)
例如,我有以下数据库。
cYear, wId, wSalary
2015, 1111, 250
2014, 1111, 270
2015, 2222, 350
2014, 3333, 400
2013, 3333, 230
2013, 4444, 350
对于wId = 1111的人,我想排除cYear = 2014的数据。另外,对于wId = 3333的人,排除cYear = 2013的数据。
所以,我想得到
cYear, wId, wSalary
2015, 1111, 250
2015, 2222, 350
2014, 3333, 400
2013, 4444, 350
我在想我可以使用group by和MAX(cYear)。所以,我创建了以下查询。
SELECT cYear, wId, wSalary FROM table WHERE cYear in (SELECT MAX(cYear) FROM table GROUP BY wId)
但是,我仍然可以获得所有数据。
我必须使用哪个查询来获取最近一年的数据集?
由于
答案 0 :(得分:0)
你可以使用它来获得每年最多一年的一条记录 -
SELECT
wId, cYear, wSalary
FROM
(SELECT
t1.*, @rn:=IF(@wId = wId, @rn + 1, IF(@wId:=wId, 1, 1)) rn
FROM
(SELECT
*
FROM
your_table
ORDER BY wId , cYear) t1
CROSS JOIN (SELECT @wId:=- 1, @rn:=0) t2) t
WHERE
rn = 1;
如果您的数据具有wId和cYear唯一的组合,则下面也应该有效。
SELECT t1.*
FROM your_table t1
INNER JOIN
( SELECT wId, MAX(cYear) cYear FROM your_table GROUP BY wId
) t2
ON t1.wId = t2.wId
AND t1.cYear = t2.cYear;
答案 1 :(得分:0)
您也可以在sql中使用Procedure。 这里 tblDemo 是你的表
Create proc usp_demo
as
begin
create table #tblTemp(pkid int primary key identity,cYear nvarchar(15), wId nvarchar(15), wSalary nvarchar(15))
create table #tblEmpList(pkid int primary key identity,wId nvarchar(15)) -- for unique wId
insert into #tblEmpList select distinct(wId) from tblDemo
--select * from #tblEmpList
DECLARE @i int
DECLARE @numrows int
DECLARE @employee_id nvarchar(30)
DECLARE @maxYear bigint
SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM #tblEmpList)
IF @numrows > 0
WHILE (@i <= (SELECT MAX(pkid) FROM #tblEmpList))
BEGIN
-- get the next employee primary key
SET @employee_id = (SELECT wId FROM #tblEmpList WHERE pkid = @i)
set @maxYear=(SELECT max(cYear) FROM tblDemo WHERE wId = @employee_id)
insert into #tblTemp select cYear , wId , wSalary from tblDemo where cYear=@maxYear and wId=@employee_id
-- increment counter for next employee
SET @i = @i + 1
END
select * from #tblTemp
drop table #tblTemp
end
exec usp_demo
输出是您需要的
答案 2 :(得分:0)
尝试使用简短查询
V2 V3 V4 V5 V6 V7 V8 V9
1 2013 3090050010 CCOU 1 22 1 N 16/03/2015
2 2013 3090050010 CCOU 1 23 1 16/03/2015
3 2013 3090050010 CCOU 2 5 1 1692528 16/03/2015
4 2013 3090430110 CCOU 15 504 2 blablablablablablablablablablablablablab labla 01/10/2014
5 2013 3090430110 CCOU 15 505 2 01/10/2014