Sql语句收藏

1、 查询列表,按照In的排序进行排序

 


select *, (select count(0from [picture] where album_id=[album].id) as piccount From [Album] Where id in (5,6,8,1,3,4order by charindex(',' + ltrim(rtrim(str(id))) + ',',',5,6,8,1,3,4,')

 

2、查询不重复结果,按照另外一个字段进行排序


select distinct A,B,max(C)
From Table
Group By A, B
Order By Max(c)

(通常情况在,A,B为用户ID和用户名,但是要按照C:添加时间来进行排序,这时候就要使用这个方法了)

 

 

1 在access数据库中

UPDATE ywx_subject SET iscurrent =iif(iscurrent,0,1);

这个语句是将数据库中的iscurrent逻辑字段取反 true改为false,false改为true

 

2 在sql server中 bit类型的字段取反

UPDATE ywx_subject SET iscurrent =iscurrent^1;

 

 

一条sql语句,查询出全部分类各前10记录

如一班级成绩表

现建立课程表 tableA

sid           sname
1             语文
2             数学
3             英语
.......

 

在建学生成绩库 tableB

id         sid           fen            name
1          1             100           张三
2          1              89            李四
3          1              95            王五
4          2             89             张三
5          3             78             王五
6          2             99             王五
.....

 

现使用

 


可以显示出所有科目前10名单

 

select a.sid,sname,id,fen,name from tableA a inner join
(
select * from tableB b
where id in(
    
select top 10 id from tableB where sid=b.sid
    
order by fen desc)) as b
on a.sid=b.sid
order by a.sid,fen desc

 

SELECT sid, sname, fen,name
FROM (SELECT px =
                  (
SELECT COUNT(1+ 1
                 
FROM tableB
                 
WHERE sid = b.sid AND fen > b.fen), a.sid, a.sname, b.fen,b.name
        
FROM tableA a JOIN
              tableB b 
ON a.sid = b.sid) t
WHERE (px <= 10)
ORDER BY sid, fen DESC

 

在放个测试用的

 


declare @tableA table(sid int ,sname varchar(20))
insert @tableA select 1,'语文'
union all select 2,'数学'
union all select 3,'英语'

declare @tableB table(id int,sid int ,fen int)
insert @tableB select 1,1,80
union all select 1,2,80
union all select 2,1,80
union all select 3,2,70
union all select 4,1,55
union all select 5,2,69
union all select 6,2,69
union all select 7,2,69
union all select 8,2,69
union all select 9,2,69
union all select 10,2,69
union all select 11,2,69
union all select 12,2,69
union all select 13,2,69
union all select 14,3,69

select a.sid,sname,id,fen from @tableA a inner join
(
select * from @tableB b
where id in(
    
select top 10 id from @tableB where sid=b.sid
    
order by fen desc)) as b
on a.sid=b.sid
order by a.sid,fen desc
posted @ 2009-05-08 19:56  冰封的心  阅读(382)  评论(0编辑  收藏  举报