我有以下格式的数据,并希望提取符号的年份= 2013年,2014年和2015年的记录。 (即那些3年,而不是2年,而不是4年)
下面的第一个(FLWS)适合,但下一个(FCCY)只有2013年和2014年,但不是15,所以我不希望它在最后一组。再往下DDD和MMM有2012年到2105,我只想要他们的2013-15数据。
我无法弄清楚为2013年,14年和15年提取3组记录所需的内部联接。任何帮助表示赞赏 感谢
Symbol Exchange Date Year
FLWS NAS 2013-05-01 2015
FLWS NAS 2013-05-01 2014
FLWS NAS 2013-05-01 2013
FCCY NAS 2013-05-01 2014
FCCY NAS 2013-05-01 2013
SRCE NAS 2013-05-01 2014
SRCE NAS 2013-05-01 2013
SRCE NAS 2013-05-01 2012
FNHC NAS 2013-05-01 2014
FNHC NAS 2013-05-01 2013
DDD NYS 2013-05-01 2015
DDD NYS 2013-05-01 2014
DDD NYS 2013-05-01 2013
DDD NYS 2013-05-01 2012
MMM NYS 2013-05-01 2015
MMM NYS 2013-05-01 2014
MMM NYS 2013-05-01 2013
MMM NYS 2013-05-01 2012
JOBS NAS 2013-05-01 2014
JOBS NAS 2013-05-01 2013
答案 0 :(得分:2)
这应该可以解决问题: 内部查询将只列出在数据库中出现3次的符号。外部查询将使用此符号名称仅为列出的符号选择所有数据。
select * from table
where symbol in ( select Symbol from table
where year in (2013, 2014, 2015)
group by symbol
having count (distinct year) = 3)
答案 1 :(得分:0)
我想我理解你的问题
Declare @Table table (Symbol varchar(25),Exchange varchar(25),Date Date,Year int)
Insert Into @Table (Symbol,Exchange,Date,Year) values
('FLWS','NAS','2013-05-01',2015),
('FLWS','NAS','2013-05-01',2014),
('FLWS','NAS','2013-05-01',2013),
('FCCY','NAS','2013-05-01',2014),
('FCCY','NAS','2013-05-01',2013),
('SRCE','NAS','2013-05-01',2014),
('SRCE','NAS','2013-05-01',2013),
('SRCE','NAS','2013-05-01',2012),
('FNHC','NAS','2013-05-01',2014),
('FNHC','NAS','2013-05-01',2013),
('DDD','NYS','2013-05-01',2015),
('DDD','NYS','2013-05-01',2014),
('DDD','NYS','2013-05-01',2013),
('DDD','NYS','2013-05-01',2012),
('MMM','NYS','2013-05-01',2015),
('MMM','NYS','2013-05-01',2014),
('MMM','NYS','2013-05-01',2013),
('MMM','NYS','2013-05-01',2012),
('JOBS','NAS','2013-05-01',2014),
('JOBS','NAS','2013-05-01',2013)
Select A.*
From @Table A
Join (Select Symbol,Hits=count(Distinct Year),MinYear=min(Year) From @Table Group By Symbol) B on (A.Symbol=B.Symbol and B.Hits=3 and B.MinYear=2013)
Order By Symbol,Year
返回
Symbol Exchange Date Year
FLWS NAS 2013-05-01 2013
FLWS NAS 2013-05-01 2014
FLWS NAS 2013-05-01 2015