作者criky (学习中)
看板Database
标题[讨论] SQL子查询
时间Thu Apr 27 00:27:57 2017
刚才板友怎麽还没问完就删掉了 XD
可能是自己试出来了吧~
总之试了一下就PO上来当练习&参考
--create table
create table score(
pname varchar(10),
subject varchar(10),
subscore integer,
id varchar(10))
;
--insert data
insert into score (pname, subject, subscore, id)
values
('张三','数学' , 90 , 1) ,
('张三','语文' , 50 , 2) ,
('张三','地里' , 40 , 3) ,
('李四','语文' , 55 , 4) ,
('李四','政治' , 45 , 5) ,
('王五','政治' , 30 , 6) ,
('造六','地里' , 90 , 7) ,
('造六','国文' , 85 , 8) ,
('造六','历史' , 100 , 9) ;
--select data: max subscore group by pname
select b.pname, subject, subscore, id from score b
join
(select pname, max(subscore) mx
from score
group by pname
) a
on a.pname = b.pname
and a.mx = b.subscore
OUTPUT
pname subject subscore id
造六 历史 100 9
张三 数学 90 1
李四 语文 55 4
王五 政治 30 6
4/29更新
另一种写法 ROW_NUMBER语法 不过没有比较简单 XD
SELECT pname, subject, subscore, id
from
(
SELECT pname, subject, subscore, id ,
ROW_NUMBER() OVER (
partition by pname
ORDER BY pname,subscore desc) N from score
) A
where A.N=1
OUTPUT
pname subject subscore id
王五 政治 30 6
李四 语文 55 4
张三 数学 90 1
造六 历史 100 9
--
不推▃▃▃▃▃▃▃▃推吗 ▲ ◤ ●\ ◤ ●\ ▎ 不推吗不推吗
不推 在这边推个文, ◣吗 / ● ● \ ▲ 不推吗不推吗
不推 就能实现愿望喔! 吗 ▊/ ◣ ◤ ◣ ◤ \ ▏ 推吗不推吗
不推吗不推吗不推吗◥█吗 │ │ ▍ 推吗不推吗
不推吗不推吗不推吗不◥吗▊ \ │ ▎ 吗不推吗
不推吗不推吗不推吗不推吗 \ ︶︶ 好人-改 / ▏ 嘿~嘿~嘿~
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 27.147.29.46
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Database/M.1493224081.A.682.html
1F:推 dogwu5566: 对,我自己试出来了XD,原来where跟in後面的条件是可以 04/27 04:22
2F:→ dogwu5566: 成对的,这是我最後的语法,select * from score where 04/27 04:23
3F:→ dogwu5566: (pname,subscore) in (select pname,max(subscore) 04/27 04:23
4F:→ dogwu5566: from score group by pname); 04/27 04:24
5F:→ dogwu5566: 不过我还没学到join关键字,我会好好研究一下,感谢! 04/27 04:25
6F:推 clonk: 没看到原来的问题 如果是mysql只要这样就好了 04/28 15:22
7F:→ clonk: select pname,subject,max(subscore) as subscore,id 04/28 15:23
8F:→ clonk: from score group by pname order by subscore desc; 04/28 15:23
※ 编辑: criky (27.147.29.46), 04/29/2017 10:22:53
9F:→ dogwu5566: 题目有说不得使用 order by 04/29 11:45
10F:→ criky: 喔,那後来补充的就不行了~~ 04/29 15:18