`
阅读更多

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);

***************************************************************************

1:找出公司里收入最高的前三名员工:

SQL> select rownum, last_name, salary
2 from (select last_name, salary
3 from s_emp
4 order by salary desc)
5 where rownum<=3;

ROWNUM LAST_NAME SALARY
---------- ------------------------- ----------
1 Velasquez 4750
2 Ropeburn 2945
3 Nguyen 2897.5

注意:请大家分析一下一下语句为什么不对:

SQL> select rownum, last_name, salary
2 from s_emp
3 where rownum<=3
4 order by salary desc;

ROWNUM LAST_NAME SALARY
---------- ------------------------- ----------
1 Velasquez 4750
3 Nagayama 2660
2 Ngao 2000

2: 找出表中的某一行或某几行的数据:

(1):找出表中第三行数据:
用以下方法是不行的,因为rownum后面至可以用<或<=号,不可以用=,>号和其它的比较符号。

SQL> select * from s_emp
2 where rownum=3;

no rows selected

SQL> select * from s_emp
2 where rownum between 3 and 5;

no rows selected

正确的方法如下:

SQL> l
1 select last_name, salary
2 from (select rownum a, b.*
3 from s_emp b)
4* where a=3
SQL> /

LAST_NAME SALARY
------------------------- ----------
Nagayama 2660

(2):找出第三行到第五行之间的数据:
SQL> l
1 select last_name, salary
2 from (select rownum a, b.*
3 from s_emp b)
4* where a between 3 and 5
SQL> /

LAST_NAME SALARY
------------------------- ----------
Nagayama 2660
Quick-To-See 2755
Ropeburn 2945

3:找出那些工资高于他们所在部门的平均工资的员工。

(1):第一种方法:
SQL> select last_name, dept_id, salary
2 from s_emp a
3 where salary>(select avg(salary)
4 from s_emp
5 where dept_id=a.dept_id);

LAST_NAME DEPT_ID SALARY
------------------------- ---------- ----------
Velasquez 50 4750
Urguhart 41 2280
Menchu 42 2375
Biri 43 2090
Catchpole 44 2470
Havel 45 2483.3
Nguyen 34 2897.5
Maduro 41 2660
Nozaki 42 2280
Schwartz 45 2090

10 rows selected.

(2):第二种方法:
SQL> l
1 select a.last_name, a.salary, a.dept_id, b.avgsal
2 from s_emp a, (select dept_id, avg(salary) avgsal
3 from s_emp
4 group by dept_id) b
5 where a.dept_id=b.dept_id
6* and a.salary>b.avgsal
SQL> /

LAST_NAME SALARY DEPT_ID AVGSAL
------------------------- ---------- ---------- ----------
Velasquez 4750 50 3847.5
Urguhart 2280 41 2181.5
Menchu 2375 42 2055.16667
Biri 2090 43 1710
Catchpole 2470 44 1995
Havel 2483.3 45 2069.1
Nguyen 2897.5 34 2204
Maduro 2660 41 2181.5
Nozaki 2280 42 2055.16667
Schwartz 2090 45 2069.1

10 rows selected.

4:找出那些工资高于他们所在部门的manager的工资的员工。

SQL> l
1 select id, last_name, salary, manager_id
2 from s_emp a
3 where salary>(select salary
4 from s_emp
5* where id=a.manager_id)
SQL> /

ID LAST_NAME SALARY MANAGER_ID
---------- ------------------------- ---------- ----------
6 Urguhart 2280 2
7 Menchu 2375 2
8 Biri 2090 2
9 Catchpole 2470 2
10 Havel 2483.3 2
12 Giljum 2831 3
13 Sedeghi 2878.5 3
14 Nguyen 2897.5 3
15 Dumas 2755 3
16 Maduro 2660 6

10 rows selected.

高级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

请问在SQL2000中怎么区分登入,用户,角色,并用例子举例说明;
  再问:
      (1)登入ID是不是就是用户名(当我创建了一个登入, 我在点击登入所对应的数据,实例中的用户一栏看到登入ID与用户名一致)

  (2)一个登入ID是不是只能对应一个用户

http://www.mscto.com

  教科书答案:登录 ID 仅能使您连接到 SQL Server 实例。特定数据库内的权限由用户帐户控制。数据库管理员将您的登录帐户映射到您有权访问的任何数据库中的用户帐户

  用户如:sa

http://www.mscto.com


  角色如:public/db_owner/db_datareader/db_datawriter等

软件开发网

  只有给用户赋予角色,该用户才有相应的操作数据库的权限 http://www.mscto.com

  如将public/db_owner角色赋给sa,则该用户有对数据库进行一切操作的权限


  角色:完成特定的、与服务器相关的管理任务所需的权限,一个用户可以属于多个角色。

  登录:仅能使您连接到 SQL Server 实例。

  命题官的理解:

  登录是sql实例级的


  用户是数据库级的

 

  角色有实例级和数据库级两种

 

  登录决定你是否能访问sql实例

 

  用户与登录对应, 确实某个登录后, 它对那些数据库有那些权限.

http://www.mscto.com


  角色是为了方便管理一类登录或者用户所具有的权限, 当某一类登录或者用户具有相同的权限时, 可以简单地给予他们对应的角色即可.


  做个形象的比喻:

 

  sql实例就相当于一个公司.

  如果你要在公司工作自然就要成为公司的员工, 因此公司的员工就相当于登录

  公司有不同的部门, 这相当于数据库, 你要在某个部门做事, 必须把你分配到某个部门, 也就是在部门的名单中要有你, 这个部门的名单就相当于用户. 名单必须对应公司的某个员工.

  但你一个人是可以在多个部门工作的

软件开发网

  因此, 一个登录可以对应多个数据库的不同用户.

  同样, 一个员工在一个部门的名单中只可能出现一次


  因此, 一个登录在同一数据库中, 只可能对应一个用户

软件开发网

  为了方便定义每个员工应该做些什么, 应该承担什么职责, 公司会定义职位, 我个职位对应的, 在数据库中就叫角色.


  因为有的职位是公司层面的, 比如懂事长, 他什么都可以管 软件开发网

  因此, 有sql实例级的角色

  也可以具体地为每个部位定义职位, 不同部门的同一名称的职位它的具体内容可以不同.


  因此,对应于sql而言, 它又有数据库级的角色

  某个员工是某个职位, 则具有该职位对应的权限与责任

  因此, 对于sql而言, 某个登录或者用户被授予某个或者某些角色, 它就具有对应的权限.


  不同职位, 在不同时期, 可以由不人担任, 换人只需要取消和授予对应人员的职位就可以了. 不用改职位定义.

  因此, 对于sql而言, 可以根据需要取消和授予某个登录或者用户的角色.
1 。SQL语句面试题关于group by 表内容:
2005-05-09 胜
2005-05-09 胜
2005-05-09 负
2005-05-09 负
2005-05-10 胜
2005-05-10 负
2005-05-10 负

如果要生成下列结果, 该如何写sql语句?

             胜 负
2005-05-09 2 2
2005-05-10 1 2
------------------------------------------
create table #tmp(rq varchar(10),shengfu nchar(1))

insert into #tmp values('2005-05-09','胜')
insert into #tmp values('2005-05-09','胜')
insert into #tmp values('2005-05-09','负')
insert into #tmp values('2005-05-09','负')
insert into #tmp values('2005-05-10','胜')
insert into #tmp values('2005-05-10','负')
insert into #tmp values('2005-05-10','负')
1)select rq, sum(case when shengfu='胜' then 1 else 0 end)'胜',sum(case when shengfu='负' then 1 else 0 end)'负' from #tmp group by rq
2) select N.rq,N.勝,M.負 from (
select rq,勝=count(*) from #tmp where shengfu='胜'group by rq)N inner join
(select rq,負=count(*) from #tmp where shengfu='负'group by rq)M on N.rq=M.rq
3)select a.col001,a.a1 胜,b.b1 负 from
(select col001,count(col001) a1 from temp1 where col002='胜' group by col001) a,
(select col001,count(col001) b1 from temp1 where col002='负' group by col001) b
where a.col001=b.col001

2.请教一个面试中遇到的SQL语句的查询问题
表中有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列,当B列大于C列时选择B列否则选择C列。
------------------------------------------
select (case when a>b then a else b end ),
(case when b>c then b esle c end)
from table_name

3.面试题:一个日期判断的sql语句?
请取出tb_send表中日期(SendTime字段)为当天的所有记录?(SendTime字段为datetime型,包含日期与时间)
------------------------------------------
select * from tb where datediff(dd,SendTime,getdate())=0

4.有一张表,里面有3个字段:语文,数学,英语。其中有3条记录分别表示语文70分,数学80分,英语58分,请用一条sql语句查询出这三条记录并按以下条件显示出来(并写出您的思路):  
   大于或等于80表示优秀,大于或等于60表示及格,小于60分表示不及格。  
       显示格式:  
       语文               数学                 英语  
       及格               优秀                 不及格    
------------------------------------------
select
(case when 语文>=80 then '优秀'
         when 语文>=60 then '及格'
else '不及格') as 语文,
(case when 数学>=80 then '优秀'
         when 数学>=60 then '及格'
else '不及格') as 数学,
(case when 英语>=80 then '优秀'
         when 英语>=60 then '及格'
else '不及格') as 英语,
from table

5.在sqlserver2000中请用sql创建一张用户临时表和系统临时表,里面包含两个字段ID和IDValues,类型都是int型,并解释下两者的区别?
------------------------------------------
用户临时表:create table #xx(ID int, IDValues int)
系统临时表:create table ##xx(ID int, IDValues int)

区别:
用户临时表只对创建这个表的用户的Session可见,对其他进程是不可见的.
当创建它的进程消失时这个临时表就自动删除.

全局临时表对整个SQL Server实例都可见,但是所有访问它的Session都消失的时候,它也自动删除.

6.sqlserver2000是一种大型数据库,他的存储容量只受存储介质的限制,请问它是通过什么方式实现这种无限容量机制的。
------------------------------------------
它的所有数据都存储在数据文件中(*.dbf),所以只要文件够大,SQL     Server的存储容量是可以扩大的.
SQL Server 2000 数据库有三种类型的文件:

主要数据文件
主要数据文件是数据库的起点,指向数据库中文件的其它部分。每个数据库都有一个主要数据文件。主要数据文件的推荐文件扩展名是 .mdf。

次要数据文件
次要数据文件包含除主要数据文件外的所有数据文件。有些数据库可能没有次要数据文件,而有些数据库则有多个次要数据文件。次要数据文件的推荐文件扩展名是 .ndf。

日志文件
日志文件包含恢复数据库所需的所有日志信息。每个数据库必须至少有一个日志文件,但可以不止一个。日志文件的推荐文件扩展名是 .ldf。

7.请用一个sql语句得出结果
从table1,table2中取出如table3所列格式数据,注意提供的数据及结果不准确,只是作为一个格式向大家请教。
如使用存储过程也可以。

table1

月份mon 部门dep 业绩yj
-------------------------------
一月份       01       10
一月份       02       10
一月份       03       5
二月份       02       8
二月份       04       9
三月份       03       8

table2

部门dep       部门名称dname
--------------------------------
       01       国内业务一部
       02       国内业务二部
       03       国内业务三部
       04       国际业务部

table3 (result)

部门dep 一月份       二月份       三月份
--------------------------------------
       01       10         null       null
       02       10         8         null
       03       null       5         8
       04       null       null       9
------------------------------------------
1)
select a.部门名称dname,b.业绩yj as '一月份',c.业绩yj as '二月份',d.业绩yj as '三月份'
from table1 a,table2 b,table2 c,table2 d
where a.部门dep = b.部门dep and b.月份mon = '一月份' and
a.部门dep = c.部门dep and c.月份mon = '二月份' and
a.部门dep = d.部门dep and d.月份mon = '三月份' and
2)
select b.depname,
sum(case when a.months = '一月份' then a.score else 0 end) as   '一月份',
sum(case when a.months = '二月份' then a.score else 0 end)   as   '二月份',
sum(case when a.months = '三月份' then a.score else 0 end) as   '三月份'
from table1 a   left join     table2 as   b on a.depno = b.depno
group by b.depname

8.华为一道面试题
一个表中的Id有多个记录,把所有这个id的记录查出来,并显示共有多少条记录数。
------------------------------------------
select id, Count(*) from tb group by id having count(*)>1
select * from(select count(ID) as count from table group by ID)T where T.count>1
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))))

Question2:Can you use a SQL statement to calculating it!
How can I print "10 to 20" for books that sell for between $10 and $20,"unknown" for books whose price is null, and "other" for all other prices?
Answer 2:
select bookid,bookname,price=case when price is null then 'unknown'
        when   price between 10 and 20 then '10 to 20' else price end
from books

Question3:Can you use a SQL statement to finding duplicate values!
How can I find authors with the same last name?
You can use the table authors in datatabase pubs. I want to get the result as below:
Output:
au_lname                                  number_dups
---------------------------------------- -----------
Ringer                                    2
(1 row(s) affected)
Answer 3
select au_lname,number_dups=count(1) from authors group by au_lname

Question4:Can you create a cross-tab report in my How can I get the report about sale quality for each store and each quarter and the total sale quality for each quarter at year 1993?
You can use the table sales and stores in datatabase pubs.
Table Sales record all sale detail item for each store. Column store_id is the id of each store, ord_date is the order date of each sale item, and column qty is the sale qulity. Table stores record all store information.
I want to get the result look like as below:
Output:
stor_name                                 Total        Qtr1         Qtr2         Qtr3         Qtr4       
---------------------------------------- ----------- ----------- ----------- ----------- -----------
Barnum's                                  50           0            50           0            0
Bookbeat                                  55           25           30           0            0
Doc-U-Mat: Quality Laundry and Books      85           0            85           0            0
Fricative Bookshop                        60           35           0            0            25
Total                                     250          60           165          0            25

Answer 4:用动态SQL实现

Question5: The Fastest Way to Recompile All Stored Procedures
I have a problem with a database running in SQL Server 6.5 (Service Pack 4). We moved the database (object transfer) from one machine to another last night, and an error (specific to a stored procedure) is cropping up. However, I can't tell which procedure is causing it. Permissions are granted in all of our stored procedures; is there a way from the isql utility to force all stored procedures to recompile?

Tips: sp_recompile can recomplie a store procedure each time
Answer 5:在执行存储过程时,使用 with recompile 选项强制编译新的计划;使用sp_recompile系统存储过程强制在下次运行时进行重新编译

Question6: How can I add row numbers to my result set?
In database pubs, have a table titles , now I want the result shown as below,each row have a row number, how can you do that?
Result:
line-no      title_id
----------- --------
1            BU1032
2            BU1111
3            BU2075
4            BU7832
5            MC2222
6            MC3021
7            MC3026
8            PC1035
9            PC8888
10           PC9999
11           PS1372
12           PS2091
13           PS2106
14           PS3333
15           PS7777
16           TC3218
17           TC4203
18           TC7777
 
Answer 6:
--SQL 2005的写法
select row_number() as line_no ,title_id from titles
--SQL 2000的写法
select line_no identity(int,1,1),title_id into #t from titles
select * from #t
drop table #t

Question 7: Can you tell me what the difference of two SQL statements at performance of execution?
Statement 1:
if NOT EXISTS ( select * from publishers where state = 'NY')
begin
SELECT 'Sales force needs to penetrate New York market'
end
else
begin
SELECT 'We have publishers in New York'
end
Statement 2:
if EXISTS ( select * from publishers where state = 'NY')
begin
SELECT 'We have publishers in New York'
end
else
begin
SELECT 'Sales force needs to penetrate New York market'
end
Answer 7:不同点:执行时的事务数,处理时间,从客户端到服务器端传送的数据量大小

Question8: How can I list all California authors regardless of whether they have written a book?
In database pubs, have a table authors and titleauthor , table authors has a column state, and titleauhtor have books each author written.
CA behalf of california in table authors.
Answer 8:
select * from   authors where state='CA'

Question9: How can I get a list of the stores that have bought both 'bussiness' and 'mod_cook' type books?
In database pubs, use three table stores,sales and titles to implement this requestment.
Now I want to get the result as below:
stor_id stor_name                               
------- ----------------------------------------
...
7896     Fricative Bookshop
...
...
...
Answer 9:
select distinct a.stor_id, a.stor_name from stores a,sales b,titles c
where a.stor_id=b.stor_id and b.title_id=c.title_id and c.type='business' and
exists(select 1 from sales k,titles g where stor_id=b.stor_id
and k.title_id=g.title_id and g.type='mod_cook')   
 


Question10: How can I list non-contignous data?
In database pubs, I create a table test using statement as below, and I insert several row as below
create table test
( id int primary key )
go

insert into test values (1 )
insert into test values (2 )
insert into test values (3 )
insert into test values (4 )
insert into test values (5 )
insert into test values (6 )
insert into test values (8 )
insert into test values (9 )
insert into test values (11)
insert into test values (12)
insert into test values (13)
insert into test values (14)
insert into test values (18)
insert into test values (19)
go

Now I want to list the result of the non-contignous row as below,how can I do it?
Missing after Missing before
------------- --------------
6              8
9              11
...

 


Answer 10:
select id from test t where not exists(select 1 from test where id=t.id+1)
or not exists(select 1 from test where id=t.id-1)

Question11: How can I list all book with prices greather than the average price of books of the same type?
In database pubs, have a table named titles , its column named price mean the price of the book, and another named type mean the type of books.
Now I want to get the result as below:
type          title                                                                             price                
------------ -------------------------------------------------------------------------------- ---------------------
business      The Busy Executive's Database Guide                                               19.9900
...
...
...
...
 
Answer 11:
select a.type,a.title,a.price from titles a,
(select type,price=avg(price) from titles group by type)b
where a.type=b.type and a.price>b.price

SQL Server!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics