常用SQL查询语句
select * from 表 group by 字段 having count(字段)>1
-------------------------------------------------------------
select *
from Information
where Name in (
select Name from Information group by name having count(*)>1)
-------------------------------------------------------------
select * from tablename where id in (
select id from tablename
group by id
having count(id) > 1
)
1.用一条SQL语句 查询出每门课都大于80分的学生姓名
name kecheng fenshu
张三 语文 81
张三 数学 75
李四 语文 76
李四 数学 90
王五 语文 81
王五 数学 100
王五 英语 90
(a)解: select distinct name from table where name not in (select distinct name from table where fenshu <= 80)
(b)解: select name from test group by name having min(fenshu) > 80
都是用到了反面求解法!(在求所有情况的的时候常用!~)
2.学生表 如下:
自动编号 学号 姓名 课程编号 课程名称分数
1 2005001 张三 0001 数学 69
2 2005002 李四 0001 数学 89
3 2005001 张三 0001 数学 69
删除除了自动编号不同,其他都相同的学生冗余信息
A: delete tablename where 自动编号 not in(select min(自动编号) from tablename group by 学号,姓名,课程编号,课程名称,分数)
3. 表A(单位名称,单位帐号), 表B(单位编号,个人账号)
列出各单位的名称,账号,以及单位的人数
select A.name, A.dwzh, isnull(Ct.Quantity,'0') as Quantity from A
left join
(select dwzh, count(*) as Quantity from B
group by dwzh) as Ct
on A.dwzh = Ct.dwzh
4. 股票表(股票代码,买卖类型,数量)
按照股票代码列出,买的数量,卖的数量。
select isnull(a.StockID, b.StockID), isnull(a.S,'0'), isnull(b.B,'0') from (
select StockID,sum(quantity) as S from stocks
where sType = 's'
group by StockID ) a
full join (
select StockID,sum(quantity) as B from stocks
where sType = 'b'
group by StockID ) b
on a.StockID = b.StockID
5. select * from tempT where ','+ tempT.description + ',' like '%,1,%'
某个表有两个字段(phone和sendtime)
phone sendtime
13908000800 2006-3-8 16:20:25
13918001800 2006-3-8 17:15:20
13908000800 2006-3-8 16:25:25
13908000800 2006-3-9 07:15:20
请写出一个sql语句,实现的功能为:取出每个号码(phone)的最新发送时间(sendtime)的记录?
select phone,max(sendtime) as sendtime from tablename group by phone
6.描述:
表1 student 学生信息表
ID int 学生编号
Name varchar 学生姓名
Sex bit 性别(男0女1)
Class int 班级编号
表2 schedule 课程信息表
ID int 课程编号
Name varchar 课程名称
表3 Grade 成绩信息表
ID int 自动编号
UID int 学生编号
SID int 课程编号
Num int 考试成绩
(a)求各班的总人数:
(b)求1班女生和男生的平均成绩
(c)各班"数据结构"(课程名称)不及格的人数:
答案:
(a) select Class,count(1) as num from student group by Class
(b) select S.Sex,avg(G.Num) as Num from student S,Grade G where S.ID=G.ID and S.Class=1 group by S.Sex
(c) select S.Class,count(1) as num from student S,Grade G,schedule SC where S.ID=G.ID and G.SID =Sc.ID and SC.Name='数据结构' and Sc.Num<60 group by S.Class
7.Question 1:Can you use a batch SQL or store procedure to calculating the Number of Days in a Month
Answer 1:找出当月的天数?
答案:select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast(cast(year(getdate()) as varchar)+'-'+cast(month(getdate()) as varchar)+'-01' as datetime))))

浙公网安备 33010602011771号