请教一个sql语句

iphilip 2016-04-21 06:07:47
有一个表Stock,里面有三个字段id,jlr,year分别代表股票代码,净利润,年度。
现在表中有的记录的最新数据year是2015年的,有的最新数据year是2014年的,怎样将所有股票的最新数据显示出来呢。
我现在是用个union语句实现,不知有没更好的写法!

select * from Stock where year=2015 and exists( select * from Stock where year=2015)
union select * from Stock where year=2014 and not exists( select * from Stock where year=2015)

有劳指点下,谢谢了
...全文
131 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
iphilip 2016-04-22
  • 打赏
  • 举报
回复
很有耐心,非常感谢,我测试这条语句也是可以的!但你的语句通用性更好!

select * from Stock  where year=2015 and id in ( select  id  from Stock where year=2015)
union select * from Stock where year=2014 and id not in ( select  id  from Stock where year=2015)
引用 4 楼 wmxcn2000 的回复:
卖水果的net 版主 2016-04-21
  • 打赏
  • 举报
回复


-- 论坛里有很多这样的例子,你可以搜索一下
-- PS: 1# 没有批评你的意思
create table test(code varchar(10),y varchar(10),price int);
insert into test values
('A','2014',100),('A','2015',80),
('B','2014',88),('B','2015',87),
('C','2014',12),('C','2015',19),
('D','2015',11),
('E','2014',11)
go
select * from test
go
with m as (
select * , row_number() over(partition by code order by y desc) rn from test
)
select code, y, price from m where rn =1 
go
drop table test
go



(8 行受影响)
code       y          price
---------- ---------- -----------
A          2014       100
A          2015       80
B          2014       88
B          2015       87
C          2014       12
C          2015       19
D          2015       11
E          2014       11

(8 行受影响)

code       y          price
---------- ---------- -----------
A          2015       80
B          2015       87
C          2015       19
D          2015       11
E          2014       11

(5 行受影响)


iphilip 2016-04-21
  • 打赏
  • 举报
回复
刚想了下

select * from Stock  where year=2015 and id in ( select  id  from Stock where year=2015)
union select * from Stock where year=2014 and id not in ( select  id  from Stock where year=2015)
引用 1 楼 py418578291 的回复:
无力吐槽了的事情
iphilip 2016-04-21
  • 打赏
  • 举报
回复
我的语句完全不对,有劳帮我写个吧,谢谢了
引用 1 楼 py418578291 的回复:
无力吐槽了的事情

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧