#
摘要: Maven,发音是[`meivin],"专家"的意思。它是一个很好的项目管理工具,很早就进入了我的必备工具行列,但是这次为了把ABPM项目完全迁移并应用maven,所以对maven进行了一些深入的学习。写这个学习笔记的目的,一个是为了自己备忘,二则希望能够为其他人学习使用maven缩短一些时间。
maven概要
首先我把maven的... 阅读全文
经常会看到这样的SQL面试题,请用一条SQL语句统计出学生的总总成绩,请用一条sql语句删除表中重复的内容,但第一条保留。最近得闲,就试着写了这么个demo,今天来这和大家分享下,如果大家有其他的sql题也可以拿出来大家一起讨论,一起分享。 先创建一个表: CREATE TABLE [dbo].[Score]( [ID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL, [Name] [nvarchar](50) NULL, [CID] [int] NULL, [Score] [int] NULL ) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('张三',1,60) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('张三',2,70) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('张三',3,80) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('张三',4,90)
INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('李四',1,60) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('李四',2,70) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('李四',3,80) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('李四',4,90)
INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('王五',1,60) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('王五',2,70) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('王五',3,80) INSERT INTO [Test].[dbo].[Score]([Name],[CID],[Score])VALUES('王五',4,90) 好了,准备工作做完了,下面我们来写两条Sql语句,解决开始提出的那两个问题 A、统计学生的成绩 select name,SUM(Score)Score from Score group by Name B、删除表中重复的记录,因为这表中的name是有重复的,所以我们就直接用这表来test delete from Score where Name in (select Name from Score group by Name having COUNT(name)>0)and ID not in (select MIN(id) from Score group by Name having COUNT(Name)>0) 好了,两条语句解决了两个问题.
Sql常见面试题(总结) 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)
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 学号,姓名,课程编号,课程名称,分数) 一个叫department的表,里面只有一个字段name,一共有4条纪录,分别是a,b,c,d,对应四个球对,现在四个球对进行比赛,用一条sql语句显示所有可能的比赛组合. 你先按你自己的想法做一下,看结果有我的这个简单吗? 答:select a.name, b.name from team a, team b where a.name < b.name
请用SQL语句实现:从TestDB数据表中查询出所有月份的发生额都比101科目相应月份的发生额高的科目。请注意:TestDB中有很多科目,都有1-12月份的发生额。 AccID:科目代码,Occmonth:发生额月份,DebitOccur:发生额。 数据库名:JcyAudit,数据集:Select * from TestDB 答:select a.* from TestDB a ,(select Occmonth,max(DebitOccur) Debit101ccur from TestDB where AccID='101' group by Occmonth) b where a.Occmonth=b.Occmonth and a.DebitOccur>b.Debit101ccur ************************************************************************************ 面试题:怎么把这样一个表儿 year month amount 1991 1 1.1 1991 2 1.2 1991 3 1.3 1991 4 1.4 1992 1 2.1 1992 2 2.2 1992 3 2.3 1992 4 2.4 查成这样一个结果 year m1 m2 m3 m4 1991 1.1 1.2 1.3 1.4 1992 2.1 2.2 2.3 2.4
答案一、 select year, (select amount from aaa m where month=1 and m.year=aaa.year) as m1, (select amount from aaa m where month=2 and m.year=aaa.year) as m2, (select amount from aaa m where month=3 and m.year=aaa.year) as m3, (select amount from aaa m where month=4 and m.year=aaa.year) as m4 from aaa group by year
这个是ORACLE 中做的: select * from (select name, year b1, lead(year) over (partition by name order by year) b2, lead(m,2) over(partition by name order by year) b3,rank()over( partition by name order by year) rk from t) where rk=1; ************************************************************************************ 精妙的SQL语句! 精妙SQL语句 作者:不详 发文时间:2003.05.29 10:55:05
说明:复制表(只复制结构,源表名:a 新表名:b)
SQL: select * into b from a where 1<>1
说明:拷贝表(拷贝数据,源表名:a 目标表名:b)
SQL: insert into b(a, b, c) select d,e,f from b;
说明:显示文章、提交人和最后回复时间
SQL: select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
说明:外连接查询(表名1:a 表名2:b)
SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
说明:日程安排提前五分钟提醒
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5
说明:两张关联表,删除主表中已经在副表中没有的信息
SQL:
delete from info where not exists ( select * from infobz where info.infid=infobz.infid )
说明:--
SQL:
SELECT A.NUM, A.NAME, B.UPD_DATE, B.PREV_UPD_DATE
FROM TABLE1,
(SELECT X.NUM, X.UPD_DATE, Y.UPD_DATE PREV_UPD_DATE
FROM (SELECT NUM, UPD_DATE, INBOUND_QTY, STOCK_ONHAND
FROM TABLE2
WHERE TO_CHAR(UPD_DATE,'YYYY/MM') = TO_CHAR(SYSDATE, 'YYYY/MM')) X,
(SELECT NUM, UPD_DATE, STOCK_ONHAND
FROM TABLE2
WHERE TO_CHAR(UPD_DATE,'YYYY/MM') =
TO_CHAR(TO_DATE(TO_CHAR(SYSDATE, 'YYYY/MM') ¦¦ '/01','YYYY/MM/DD') - 1, 'YYYY/MM') ) Y,
WHERE X.NUM = Y.NUM (+)
AND X.INBOUND_QTY + NVL(Y.STOCK_ONHAND,0) <> X.STOCK_ONHAND ) B
WHERE A.NUM = B.NUM
说明:--
SQL:
select * from studentinfo where not exists(select * from student where studentinfo.id=student.id) and 系名称='"&strdepartmentname&"' and 专业名称='"&strprofessionname&"' order by 性别,生源地,高考总成绩
说明:
从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源)
SQL:
SELECT a.userper, a.tel, a.standfee, TO_CHAR(a.telfeedate, 'yyyy') AS telyear,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '01', a.factration)) AS JAN,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '02', a.factration)) AS FRI,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '03', a.factration)) AS MAR,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '04', a.factration)) AS APR,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '05', a.factration)) AS MAY,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '06', a.factration)) AS JUE,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '07', a.factration)) AS JUL,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '08', a.factration)) AS AGU,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '09', a.factration)) AS SEP,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '10', a.factration)) AS OCT,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '11', a.factration)) AS NOV,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '12', a.factration)) AS DEC
FROM (SELECT a.userper, a.tel, a.standfee, b.telfeedate, b.factration
FROM TELFEESTAND a, TELFEE b
WHERE a.tel = b.telfax) a
GROUP BY a.userper, a.tel, a.standfee, TO_CHAR(a.telfeedate, 'yyyy')
说明:四表联查问题:
SQL: select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....
说明:得到表中最小的未使用的ID号
SQL:
SELECT (CASE WHEN EXISTS(SELECT * FROM Handle b WHERE b.HandleID = 1) THEN MIN(HandleID) + 1 ELSE 1 END) as HandleID
FROM Handle
WHERE NOT HandleID IN (SELECT a.HandleID - 1 FROM Handle a)
******************************************************************************* 有两个表A和B,均有key和value两个字段,如果B的key在A中也有,就把B的value换为A中对应的value 这道题的SQL语句怎么写? update b set b.value=(select a.value from a where a.key=b.key) where b.id in(select b.id from b,a where b.key=a.key); *************************************************************************** 高级sql面试题 原表: courseid coursename score ------------------------------------- 1 java 70 2 oracle 90 3 xml 40 4 jsp 30 5 servlet 80 ------------------------------------- 为了便于阅读,查询此表后的结果显式如下(及格分数为60): courseid coursename score mark --------------------------------------------------- 1 java 70 pass 2 oracle 90 pass 3 xml 40 fail 4 jsp 30 fail 5 servlet 80 pass --------------------------------------------------- 写出此查询语句 没有装ORACLE,没试过 select courseid, coursename ,score ,decode(sign(score-60),-1,'fail','pass') as mark from course 完全正确
SQL> desc course_v Name Null? Type ----------------------------------------- -------- ---------------------------- COURSEID NUMBER COURSENAME VARCHAR2(10) SCORE NUMBER
SQL> select * from course_v;
COURSEID COURSENAME SCORE ---------- ---------- ---------- 1 java 70 2 oracle 90 3 xml 40 4 jsp 30 5 servlet 80
SQL> select courseid, coursename ,score ,decode(sign(score-60),-1,'fail','pass') as mark from course_v;
COURSEID COURSENAME SCORE MARK ---------- ---------- ---------- ---- 1 java 70 pass 2 oracle 90 pass 3 xml 40 fail 4 jsp 30 fail 5 servlet 80 pass ******************************************************************************* 原表:
id proid proname 1 1 M 1 2 F 2 1 N 2 2 G 3 1 B 3 2 A 查询后的表:
id pro1 pro2 1 M F 2 N G 3 B A 写出查询语句 解决方案
sql求解 表a 列 a1 a2 记录 1 a 1 b 2 x 2 y 2 z 用select能选成以下结果吗? 1 ab 2 xyz 使用pl/sql代码实现,但要求你组合后的长度不能超出oracle varchar2长度的限制。 下面是一个例子 create or replace type strings_table is table of varchar2(20); / create or replace function merge (pv in strings_table) return varchar2 is ls varchar2(4000); begin for i in 1..pv.count loop ls := ls || pv(i); end loop; return ls; end; / create table t (id number,name varchar2(10)); insert into t values(1,'Joan'); insert into t values(1,'Jack'); insert into t values(1,'Tom'); insert into t values(2,'Rose'); insert into t values(2,'Jenny');
column names format a80; select t0.id,merge(cast(multiset(select name from t where t.id = t0.id) as strings_table)) names from (select distinct id from t) t0;
drop type strings_table; drop function merge; drop table t;
用sql:
Well if you have a thoretical maximum, which I would assume you would given the legibility of listing hundreds of employees in the way you describe then yes. But the SQL needs to use the LAG function for each employee, hence a hundred emps a hundred LAGs, so kind of bulky.
This example uses a max of 6, and would need more cut n pasting to do more than that.
SQL> select deptno, dname, emps 2 from ( 3 select d.deptno, d.dname, rtrim(e.ename ||', '|| 4 lead(e.ename,1) over (partition by d.deptno 5 order by e.ename) ||', '|| 6 lead(e.ename,2) over (partition by d.deptno 7 order by e.ename) ||', '|| 8 lead(e.ename,3) over (partition by d.deptno 9 order by e.ename) ||', '|| 10 lead(e.ename,4) over (partition by d.deptno 11 order by e.ename) ||', '|| 12 lead(e.ename,5) over (partition by d.deptno 13 order by e.ename),', ') emps, 14 row_number () over (partition by d.deptno 15 order by e.ename) x 16 from emp e, dept d 17 where d.deptno = e.deptno 18 ) 19 where x = 1 20 /
DEPTNO DNAME EMPS ------- ----------- ------------------------------------------ 10 ACCOUNTING CLARK, KING, MILLER 20 RESEARCH ADAMS, FORD, JONES, ROONEY, SCOTT, SMITH 30 SALES ALLEN, BLAKE, JAMES, MARTIN, TURNER, WARD
also 先create function get_a2; create or replace function get_a2( tmp_a1 number) return varchar2 is Col_a2 varchar2(4000); begin Col_a2:=''; for cur in (select a2 from unite_a where a1=tmp_a1) loop Col_a2=Col_a2||cur.a2; end loop; return Col_a2; end get_a2;
select distinct a1 ,get_a2(a1) from unite_a 1 ABC 2 EFG 3 KMN ******************************************************************************* 一个SQL 面试题 去年应聘一个职位未果,其间被考了一个看似简单的题,但我没有找到好的大案. 不知各位大虾有无好的解法?
题为: 有两个表, t1, t2, Table t1:
SELLER | NON_SELLER ----- -----
A B A C A D B A B C B D C A C B C D D A D B D C
Table t2:
SELLER | COUPON | BAL ----- --------- --------- A 9 100 B 9 200 C 9 300 D 9 400 A 9.5 100 B 9.5 20 A 10 80
要求用SELECT 语句列出如下结果:------如A的SUM(BAL)为B,C,D的和,B的SUM(BAL)为A,C,D的和....... 且用的方法不要增加数据库负担,如用临时表等.
NON-SELLER| COUPON | SUM(BAL) ------- -------- A 9 900 B 9 800 C 9 700 D 9 600 A 9.5 20 B 9.5 100 C 9.5 120 D 9.5 120 A 10 0 B 10 80 C 10 80 D 10 80 关于论坛上那个SQL微软面试题 问题:
一百个账户各有100$,某个账户某天如有支出则添加一条新记录,记录其余额。一百天后,请输出每天所有账户的余额信息
这个问题的难点在于每个用户在某天可能有多条纪录,也可能一条纪录也没有(不包括第一天)
返回的记录集是一个100天*100个用户的纪录集
下面是我的思路:
1.创建表并插入测试数据:我们要求username从1-100 CREATE TABLE [dbo].[TABLE2] ( [username] [varchar] (50) NOT NULL , --用户名 [outdate] [datetime] NOT NULL , --日期 [cash] [float] NOT NULL --余额 ) ON [PRIMARY
declare @i int set @i=1 while @i<=100 begin insert table2 values(convert(varchar(50),@i),'2001-10-1',100) insert table2 values(convert(varchar(50),@i),'2001-11-1',50) set @i=@i+1 end insert table2 values(convert(varchar(50),@i),'2001-10-1',90)
select * from table2 order by outdate,convert(int,username)
2.组合查询语句: a.我们必须返回一个从第一天开始到100天的纪录集: 如:2001-10-1(这个日期是任意的) 到 2002-1-8 由于第一天是任意一天,所以我们需要下面的SQL语句: select top 100 dateadd(d,convert(int,username)-1,min(outdate)) as outdate from table2 group by username order by convert(int,username) 这里的奥妙在于: convert(int,username)-1(记得我们指定用户名从1-100 :-)) group by username,min(outdate):第一天就可能每个用户有多个纪录。 返回的结果: outdate ------------------------------------------------------ 2001-10-01 00:00:00.000 ......... 2002-01-08 00:00:00.000
b.返回一个所有用户名的纪录集: select distinct username from table2 返回结果: username -------------------------------------------------- 1 10 100 ...... 99
c.返回一个100天记录集和100个用户记录集的笛卡尔集合: select * from ( select top 100 dateadd(d,convert(int,username)-1,min(outdate)) as outdate from table2 group by username order by convert(int,username) ) as A CROSS join ( select distinct username from table2 ) as B order by outdate,convert(int,username) 返回结果100*100条纪录: outdate username 2001-10-01 00:00:00.000 1 ...... 2002-01-08 00:00:00.000 100
d.返回当前所有用户在数据库的有的纪录: select outdate,username,min(cash) as cash from table2 group by outdate,username
order by outdate,convert(int,username) 返回纪录: outdate username cash 2001-10-01 00:00:00.000 1 90 ...... 2002-01-08 00:00:00.000 100 50
e.将c中返回的笛卡尔集和d中返回的纪录做left join: select C.outdate,C.username, D.cash from ( select * from ( select top 100 dateadd(d,convert(int,username)-1,min(outdate)) as outdate from table2 group by username order by convert(int,username) ) as A CROSS join ( select distinct username from table2 ) as B ) as C left join ( select outdate,username,min(cash) as cash from table2 group by outdate,username ) as D on(C.username=D.username and datediff(d,C.outdate,D.outdate)=0)
order by C.outdate,convert(int,C.username) 注意:用户在当天如果没有纪录,cash字段返回NULL,否则cash返回每个用户当天的余额 outdate username cash 2001-10-01 00:00:00.000 1 90 2001-10-01 00:00:00.000 2 100 ...... 2001-10-02 00:00:00.000 1 90 2001-10-02 00:00:00.000 2 NULL <--注意这里 ......
2002-01-08 00:00:00.000 100 50
f.好了,现在我们最后要做的就是,如果cash为NULL,我们要返回小于当前纪录日期的第一个用户余额(由于我们使用order by cash,所以返回top 1纪录即可,使用min应该也可以),这个余额即为当前的余额: case isnull(D.cash,0) when 0 then ( select top 1 cash from table2 where table2.username=C.username and datediff(d,C.outdate,table2.outdate)<0 order by table2.cash ) else D.cash end as cash
g.最后组合的完整语句就是 select C.outdate,C.username, case isnull(D.cash,0) when 0 then ( select top 1 cash from table2 where table2.username=C.username and datediff(d,C.outdate,table2.outdate)<0 order by table2.cash ) else D.cash end as cash from ( select * from ( select top 100 dateadd(d,convert(int,username)-1,min(outdate)) as outdate from table2 group by username order by convert(int,username) ) as A CROSS join ( select distinct username from table2 ) as B ) as C left join ( select outdate,username,min(cash) as cash from table2 group by outdate,username ) as D on(C.username=D.username and datediff(d,C.outdate,D.outdate)=0)
order by C.outdate,convert(int,C.username)
返回结果: outdate username cash 2001-10-01 00:00:00.000 1 90 2001-10-01 00:00:00.000 2 100 ...... 2002-01-08 00:00:00.000 100 50 *********************************************************************************** 取出sql表中第31到40的记录(以自动增长ID为主键) *从数据表中取出第n条到第m条的记录*/
declare @m int declare @n int declare @sql varchar(800) set @m=40 set @n=31 set @sql='select top '+str(@m-@n+1) + '* from idetail where autoid not in( select top '+ str(@n-1) + 'autoid from idetail)' exec(@sql)
select top 10 * from t where id not in (select top 30 id from t order by id ) orde by id -------------------------------------------------------------------------------- select top 10 * from t where id in (select top 40 id from t order by id) order by id desc
******************************************************************************* 一道面试题,写sql语句
有表a存储二叉树的节点,要用一条sql语句查出所有节点及节点所在的层. 表a c1 c2 A ----------1 ---- ---- / \ A B B C --------2 A C / / \ B D D N E ------3 C E / \ \ D F F K I ---4 E I D K C N
所要得到的结果如下
jd cs ----- ---- A 1 B 2 C 2 D 3 N 3 E 3 F 4 K 4 I 4 有高手指导一下,我只能用pl/sql写出来,请教用一条sql语句的写法 SQL> select c2, level + 1 lv 2 from test start 3 with c1 = 'A' 4 connect by c1 = prior c2 5 union 6 select 'A', 1 from dual 7 order by lv;
C2 LV -- ---------- A 1 B 2 C 2 D 3 E 3 N 3 F 4 I 4 K 4
已选择9行。
Student(S#,Sname,Sage,Ssex) 学生表 Course(C#,Cname,T#) 课程表 SC(S#,C#,score) 成绩表 Teacher(T#,Tname) 教师表 问题: 1、查询“001”课程比“002”课程成绩高的所有学生的学号; select a.S# from (select s#,score from SC where C#=’001′) a, (select s#,score from SC where C#=’002′) b where a.score>b.score and a.s#=b.s#; 2、查询平均成绩大于60分的同学的学号和平均成绩; select S#,avg(score) from sc group by S# having avg(score) >60; 3、查询所有同学的学号、姓名、选课数、总成绩; select Student.S#,Student.Sname,count(SC.C#),sum(score) from Student left Outer join SC on Student.S#=SC.S# group by Student.S#,Sname 4、查询姓“李”的老师的个数; select count(distinct(Tname)) from Teacher where Tname like ‘李%’; 5、查询没学过“叶平”老师课的同学的学号、姓名; select Student.S#,Student.Sname from Student where S# not in (select distinct( SC.S#) from SC,Course,Teacher where SC.C#=Course.C# and Teacher.T#=Course.T# and Teacher.Tname=’叶平’); 6、查询学过“001”并且也学过编号“002”课程的同学的学号、姓名; select Student.S#,Student.Sname from Student,SC where Student.S#=SC.S# and SC.C#=’001′and exists( Select * from SC as SC_2 where SC_2.S#=SC.S# and SC_2.C#=’002′); 7、查询学过“叶平”老师所教的所有课的同学的学号、姓名; select S#,Sname from Student where S# in (select S# from SC ,Course ,Teacher where SC.C#=Course.C# and Teacher.T#=Course.T# and Teacher.Tname=’叶平’ group by S# having count(SC.C#)=(select count(C#) from Course,Teacher where Teacher.T#=Course.T# and Tname=’叶平’)); 8、查询所有课程成绩小于60分的同学的学号、姓名; select S#,Sname from Student where S# not in (select Student.S# from Student,SC where S.S#=SC.S# and score>60); 9、查询没有学全所有课的同学的学号、姓名; select Student.S#,Student.Sname from Student,SC where Student.S#=SC.S# group by Student.S#,Student.Sname having count(C#) <(select count(C#) from Course); 10、查询至少有一门课与学号为“1001”的同学所学相同的同学的学号和姓名; select S#,Sname from Student,SC where Student.S#=SC.S# and C# in (select C# from SC where S#='1001'); 11、删除学习“叶平”老师课的SC表记录; Delect SC from course ,Teacher where Course.C#=SC.C# and Course.T#= Teacher.T# and Tname='叶平'; 12、查询各科成绩最高和最低的分:以如下形式显示:课程ID,最高分,最低分 SELECT L.C# 课程ID,L.score 最高分,R.score 最低分 FROM SC L ,SC R WHERE L.C# = R.C# and L.score = (SELECT MAX(IL.score) FROM SC IL,Student IM WHERE IL.C# = L.C# and IM.S#=IL.S# GROUP BY IL.C#) and R.Score = (SELECT MIN(IR.score) FROM SC IR WHERE IR.C# = R.C# GROUP BY IR.C# ); 13、查询学生平均成绩及其名次 SELECT 1+(SELECT COUNT( distinct 平均成绩) FROM (SELECT S#,AVG(score) 平均成绩 FROM SC GROUP BY S# ) T1 WHERE 平均成绩 > T2.平均成绩) 名次, S# 学生学号,平均成绩 FROM (SELECT S#,AVG(score) 平均成绩 FROM SC GROUP BY S# ) T2 ORDER BY 平均成绩 desc; 14、查询各科成绩前三名的记录:(不考虑成绩并列情况) SELECT t1.S# as 学生ID,t1.C# as 课程ID,Score as 分数 FROM SC t1 WHERE score IN (SELECT TOP 3 score FROM SC WHERE t1.C#= C# ORDER BY score DESC) ORDER BY t1.C#; 15、查询每门功成绩最好的前两名 SELECT t1.S# as 学生ID,t1.C# as 课程ID,Score as 分数 FROM SC t1 WHERE score IN (SELECT TOP 2 score FROM SC WHERE t1.C#= C# ORDER BY score DESC ) ORDER BY t1.C#; 补充: 已经知道原表 year salary —————— 2000 1000 2001 2000 2002 3000 2003 4000 解: select b.year,sum(a.salary) from salary a,salary b where a.year<=b.year group by b.year order by b.year; 在面试过程中多次碰到一道SQL查询的题目,查询A(ID,Name)表中第31至40条记录,ID作为主键可能是不是连续增长的列,完整的查询语句如下: 方法一: select top 10 * from A where ID >(select max(ID) from (select top 30 ID from A order by ID ) T) order by ID 方法二: select top 10 * from A where ID not In (select top 30 ID from A order by ID) order by ID
这几天做项目,需要一个消息提醒功能,决定用 dwr实现,在 dwr官网和网上找了很多资料,也没实现精准推送,大多数的例子具体步骤写的不清楚,不怎么了解 dwr的人看了也未必能看懂,反正我是没看懂,那时就决定,若自己实现了,一定将具体步骤写下来,希望能给那些和我一样的人一些帮助,若有不明白的,可以给小弟留言。我只写步骤,不写原理,下面开始。 第一、在项目中引入dwr.jar,然后在web.xml中进行配置,配置如下: <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class> org.directwebremoting.servlet.DwrServlet </servlet-class> <init-param> <param-name>crossDomainSessionSecurity</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>allowScriptTagRemoting</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>classes</param-name> <param-value>java.lang.Object</param-value> </init-param> <init-param> <param-name>activeReverseAjaxEnabled</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>initApplicationScopeCreatorsAtStartup</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>maxWaitAfterWrite</param-name> <param-value>3000</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>logLevel</param-name> <param-value>WARN</param-value> </init-param> </servlet> 第二:在web.xml的同级目录下新建dwr.xml文件,内容如下 <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd"> <dwr> <alow> <create creator="new" javascript="MessagePush"> <param name="class" value="com.huatech.messageremind.service.MessagePush"/> </create> </alow> </dwr> 这个是dwr的基本配置,MessagePush在页面的javascript中使用,com.huatech.messageremind.service.MessagePush实现了想要调用的方法,MessagePush我觉得就相当于java类中的一个映射,在javascript中使用MessagePush.java类中实现的方法,即可在dwr中调用。 第三,要想使用dwr,还要在你想要推送的页面中引入script, <script type="text/javascript" src="<%=basepath%>dwr/engine.js"></script> <script type="text/javascript" src="<%=basepath%>dwr/util.js"></script> <script type="text/javascript" src="<%=basepath%>dwr/interface/MessagePush.js"></script> 可以看见,也引入了dwr.xml中配置的javascript,engine.js和util.js是必须引入的。 以上三点都是基本配置,没什么好说的,想使用dwr,就得这么做。 第四,实现消息的精准推送 消息推送简单,但是想实现精准推送就需要做一些别的操作了 1 在任何一个用户登录的时候,都需要将其userId或者其他唯一性标识放入session中,我放的是userId, 这里就以 userId为唯一性标识。 2 在载入想推送的页面时,需要onload一个我在MessagePush类中实现的方法,当然了,需要使用dwr调用 js的调用方法如下: function onPageLoad(){ var userId = '${userinfo.humanid}'; MessagePush.onPageLoad(userId); } <body onload="dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);onPageLoad();> 在onload中的三个函数都是必须的,其中dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);是dwr中的函数。 MessagePush类中实现的方法如下: public void onPageLoad(String userId) { ScriptSession scriptSession = WebContextFactory.get().getScriptSession(); scriptSession.setAttribute(userId, userId); DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil(); try { dwrScriptSessionManagerUtil.init(); } catch (ServletException e) { e.printStackTrace(); } } 大家注意到,onPageLoad方法中还有一个名为DwrScriptSessionManagerUtil的类,该类如下实现: public class DwrScriptSessionManagerUtil extends DwrServlet{ private static final long serialVersionUID = -7504612622407420071L; public void init() throws ServletException { Container container = ServerContextFactory.get().getContainer(); ScriptSessionManager manager = container .getBean(ScriptSessionManager.class); ScriptSessionListener listener = new ScriptSessionListener() { public void sessionCreated(ScriptSessionEvent ev) { HttpSession session = WebContextFactory.get().getSession(); String userId =((User) session.getAttribute("userinfo")).getHumanid()+""; System.out.println("a ScriptSession is created!"); ev.getSession().setAttribute("userId", userId); } public void sessionDestroyed(ScriptSessionEvent ev) { System.out.println("a ScriptSession is distroyed"); } }; manager.addScriptSessionListener(listener); } } 第四步是最最重要的,为了第四步我研究了两天多,下面开始消息推送。 第五、消息推送 在你想要推送消息的时候,调用如下方法: public void sendMessageAuto(String userid,String message) { final String userId = userid ; final String autoMessage = message; Browser.withAllSessionsFiltered(new ScriptSessionFilter() { public boolean match(ScriptSession session) { if (session.getAttribute("userId") == null) return false; else return (session.getAttribute("userId")).equals(userId); } }, new Runnable(){ private ScriptBuffer script = new ScriptBuffer(); public void run() { script.appendCall("showMessage", autoMessage); Collection<ScriptSession> sessions = Browser .getTargetSessions(); for (ScriptSession scriptSession : sessions) { scriptSession.addScript(script); } } }); } userid即为你想推给消息的人,message为你想推送的消息,大家注意到这里script.appendCall("showMessage", autoMessage); 其中showMessage为在想推送的页面中的javascript方法,autoMessage是这个方法的参数,这样那个页面就能得到推送的内容了,至于如何展现,就看你的需要了。 至此,一个dwr消息精准推送的步骤就写完了,其实很多东西都不难,只是我们不知道该怎么用而已。
1.下载ActiveMQ
去官方网站下载:http://activemq.apache.org/
2.运行ActiveMQ
解压缩apache-activemq-5.5.1-bin.zip,然后双击apache-activemq-5.5.1\bin\activemq.bat运行ActiveMQ程序。
启动ActiveMQ以后,登陆:http://localhost:8161/admin/,创建一个Queue,命名为FirstQueue。
3.创建Eclipse项目并运行
创建project:ActiveMQ-5.5,并导入apache-activemq-5.5.1\lib目录下需要用到的jar文件,项目结构如下图所示:
3.1.Sender.java
package com.xuwei.activemq;
import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory;
public class Sender { private static final int SEND_NUMBER = 5;
public static void main(String[] args) { // ConnectionFactory :连接工厂,JMS 用它创建连接 ConnectionFactory connectionFactory; // Connection :JMS 客户端到JMS Provider 的连接 Connection connection = null; // Session: 一个发送或接收消息的线程 Session session; // Destination :消息的目的地;消息发送给谁. Destination destination; // MessageProducer:消息发送者 MessageProducer producer; // TextMessage message; // 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar connectionFactory = new ActiveMQConnectionFactory( ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616"); try { // 构造从工厂得到连接对象 connection = connectionFactory.createConnection(); // 启动 connection.start(); // 获取操作连接 session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置 destination = session.createQueue("FirstQueue"); // 得到消息生成者【发送者】 producer = session.createProducer(destination); // 设置不持久化,此处学习,实际根据项目决定 producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // 构造消息,此处写死,项目就是参数,或者方法获取 sendMessage(session, producer); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != connection) connection.close(); } catch (Throwable ignore) { } } }
public static void sendMessage(Session session, MessageProducer producer) throws Exception { for (int i = 1; i <= SEND_NUMBER; i++) { TextMessage message = session .createTextMessage("ActiveMq 发送的消息" + i); // 发送消息到目的地方 System.out.println("发送消息:" + "ActiveMq 发送的消息" + i); producer.send(message); } } }
3.2.Receiver.java
package com.xuwei.activemq;
import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory;
public class Receiver { public static void main(String[] args) { // ConnectionFactory :连接工厂,JMS 用它创建连接 ConnectionFactory connectionFactory; // Connection :JMS 客户端到JMS Provider 的连接 Connection connection = null; // Session: 一个发送或接收消息的线程 Session session; // Destination :消息的目的地;消息发送给谁. Destination destination; // 消费者,消息接收者 MessageConsumer consumer; connectionFactory = new ActiveMQConnectionFactory( ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616"); try { // 构造从工厂得到连接对象 connection = connectionFactory.createConnection(); // 启动 connection.start(); // 获取操作连接 session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); // 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置 destination = session.createQueue("FirstQueue"); consumer = session.createConsumer(destination); while (true) { //设置接收者接收消息的时间,为了便于测试,这里谁定为100s TextMessage message = (TextMessage) consumer.receive(100000); if (null != message) { System.out.println("收到消息" + message.getText()); } else { break; } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != connection) connection.close(); } catch (Throwable ignore) { } } } }
4.注意事项
- 最后接收者跟发送者在不同的机器上测试
- 项目所引用的jar最后在ActiveMQ下的lib中找,这样不会出现版本冲突。
5.测试过程
因为是在单机上测试,所以需要开启两个eclipse,每一个eclipse都有自身的workspace。我们在eclipse1中运行Receiver,在eclipse2中运行Sender。
刚开始eclipse1中运行Receiver以后console介面没有任何信息,在eclipse2中运行Sender以后,eclipse2中的console显示如下信息:
发送消息:ActiveMq 发送的消息1 发送消息:ActiveMq 发送的消息2 发送消息:ActiveMq 发送的消息3 发送消息:ActiveMq 发送的消息4 发送消息:ActiveMq 发送的消息5
而回到eclipse1中发现console界面出现如下信息:
收到消息ActiveMq 发送的消息1 收到消息ActiveMq 发送的消息2 收到消息ActiveMq 发送的消息3 收到消息ActiveMq 发送的消息4 收到消息ActiveMq 发送的消息5
PS:2012-2-27
今天发现测试并不需要开启两个eclipse,在一个eclipse下页可以启动多个程序,并且有多个console,在上面的Receiver.java中,设置一个较大的时间,比如receive(500000),如下代码所示:
TextMessage message = (TextMessage) consumer.receive(500000);
这个时候运行Receiver.java的话,会使得这个Receiver.java一直运行500秒,在eclipse中可以发现:
点击那个红色方块可以手动停止运行程序。
运行玩receiver以后我们在运行sender,在运行完sender以后,我们要切换到receiver的console,如下图所示:
http://www.cnblogs.com/xwdreamer/archive/2012/02/21/2360818.html
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>js实现checkbox全选,反选,全不选</title> </head> <script type="text/javascript" src="js/jquery-1.6.4.js"></script> <script type="text/javascript"> //复选框全选 function checkAll(formvalue) { var roomids = document.getElementsByName(formvalue); for ( var j = 0; j < roomids.length; j++) { if (roomids.item(j).checked == false) { roomids.item(j).checked = true; } } }
//复选框全不选 function uncheckAll(formvalue) { var roomids = document.getElementsByName(formvalue); for ( var j = 0; j < roomids.length; j++) { if (roomids.item(j).checked == true) { roomids.item(j).checked = false; } } }
//复选框选择转换 function switchAll(formvalue) { var roomids = document.getElementsByName(formvalue); for ( var j = 0; j < roomids.length; j++) { roomids.item(j).checked = !roomids.item(j).checked; } } </script> </head> <body> <input type="radio" name="all" id="all" onclick="checkAll('test')" /> 全选 <input type="radio" name="all" id="Checkbox1" onclick="uncheckAll('test')" /> 全不选 <input type="radio" name="all" id="Checkbox2" onclick="switchAll('test')" /> 反选 <br /> <input name="test" value="复选框1" type="checkbox" /> 复选框1 <br /> <input name="test" value="复选框2" type="checkbox" /> 复选框2 <br /> <input name="test" value="复选框3" type="checkbox" /> 复选框3 <br /> <input name="test" value="复选框4" type="checkbox" /> 复选框4 <br /> <input name="test" value="复选框5" type="checkbox" /> 复选框5 <br /> <input name="test" value="复选框6" type="checkbox" /> 复选框6 <br /> </body> </html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>js test</title> </head> <script type="text/javascript" src="js/jquery-1.6.4.js"></script> <script type="text/javascript"> function selectAll(){ var name=document.getElementsByName('checkbox'); for(var i=0;i<name.length;i++){ if(name.item(i).checked==false) name.item(i).checked=true; } } </script> <body> <form name="myForm" method="post" action="CheckValue"> 全选:<input type="radio" name="all" id="all" onclick="selectAll('checkebox')" /><br/> 表单名称1: <input type="checkbox" name="checkbox" value="checkbox1" /><br/> 表单名称2: <input type="checkbox" name="checkbox" value="checkbox2" /><br/> 表单名称3: <input type="checkbox" name="checkbox" value="checkbox3" /><br/> 表单名称4: <input type="checkbox" name="checkbox" value="checkbox4" /><br/> 表单名称5: <input type="checkbox" name="checkbox" value="checkbox5" /><br/> 表单名称6: <input type="checkbox" name="checkbox" value="checkbox6" /><br/> <input type="submit" value="提交"/> </form>
</body> </html> <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>abs</display-name> <servlet> <servlet-name>CheckValue</servlet-name> <servlet-class>org.abin.lee.servlet.CheckValue</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckValue</servlet-name> <url-pattern>/CheckValue</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app> package org.abin.lee.servlet;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class CheckValue extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String[] value=req.getParameterValues("checkbox"); for(int i=0;i<value.length;i++){ System.out.println("第"+i+"个:"+value[i]); } } }
<script language=javascript> //第一种方法 function selectall1() { var a = document.getElementsByTagName("input"); if(a[0].checked==true){ for (var i=0; i<a.length; i++) if (a[i].type == "checkbox") a[i].checked = false; } else { for (var i=0; i<a.length; i++) if (a[i].type == "checkbox") a[i].checked = true; } }
//第二种方法
function selectall2() { var tform = document.forms['form1']; for (var i=0;i<tform.length;i++) { var e = tform.elements[i]; if (e.type == "checkbox") e.checked = !e.checked; } }
//第三种方法,结合上述两种方法 function selectall3() { var a = document.getElementsByTagName("input"); for (var i=0; i<a.length; i++) if (a[i].type == "checkbox") a[i].checked =!a[i].checked; } //第四种方法 function selectall4(id){ //用id区分 var tform=document.forms['form1']; for(var i=0;i<tform.length;i++){ var e=tform.elements[i]; if(e.type=="checkbox" && e.name==id) e.checked=!e.checked; } } //第五种方法 function selectall(theform,thename){ //theform指定的form,thename是checkbox的name属性 var tform=document.forms[theform]; document.getElementById("thewen").value='反选'; for(var i=0;i<tform.length;i++){ var e=tform.elements[i]; if(e.type=='checkbox' && e.name==thename)e.checked=!e.checked; } } </script> <form id="form1" name="form1" method="post" action=""> <input type="checkbox" name="sid" value="1" /> <input name="thes" type="button" onclick="javascript:selectall3()" value="全选" /> </form>
|