求SQL查询语句(图书管理系统查询借阅次数)
表一(书种表)id唯一
id(编号) title(书名) price(价格)
1001 语文教材 10
1002 数学教材 20
1003 外语教材 30
。。。。。。。
表二(书册表) 一种书有多册,条码不同,id相同
id(编号) numer(图书条形码) adress(典藏地点)
1001 2012001 第一教室
1001 2012002 第一教室
1001 2012003 教材室
1002 2012004 第一教室
1002 2012005 教材室
1003 。。。。。。。。。
表三(借阅表)
num(还书编号)readid(读者条码)numer(图书条码)staic(图书状态)name(操作员)
hs00001 dz001 2012001 还 XX
hs00002 dz001 2012005 未 XX
hs00003 dz002 2012002 还 XX
hs00004 dz002 2012001 未 XX
。。。。。。
借出一本书就在表三产生一条记录,书的状态分为“还”和“未还”
现在要统计每一种的借阅次数
比如1001这一种书(多册)总共借出多少次(还和未的都算一次)
还有,一次都没借出的书种有那些
这个SQL语句该怎么写?请教大家,谢谢
[解决办法]
----------------------------
-- Author :TravyLee(物是人非事事休,欲语泪先流!)
-- Date :2012-11-23 10:09:54
-- Version:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
--Jul 9 2008 14:43:34
--Copyright (c) 1988-2008 Microsoft Corporation
--Developer Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[书种表]
if object_id('[书种表]') is not null drop table [书种表]
go
create table [书种表]([id] int,[title] varchar(8),[price] int)
insert [书种表]
select 1001,'语文教材',10 union all
select 1002,'数学教材',20 union all
select 1003,'外语教材',30
--> 测试数据:[书册表]
if object_id('[书册表]') is not null drop table [书册表]
go
create table [书册表]([id] int,[numer] int,[adress] varchar(8))
insert [书册表]
select 1001,2012001,'第一教室' union all
select 1001,2012002,'第一教室' union all
select 1001,2012003,'教材室' union all
select 1002,2012004,'第一教室' union all
select 1002,2012005,'教材室'
--> 测试数据:[借阅表]
if object_id('[借阅表]') is not null drop table [借阅表]
go
create table [借阅表](
[num] varchar(7),
[readid] varchar(5),
[numer] int,
[staic] varchar(2),
[name] varchar(2)
)
insert [借阅表]
select 'hs00001','dz001',2012001,'还','XX' union all
select 'hs00002','dz001',2012005,'未','XX' union all
select 'hs00003','dz002',2012002,'还','XX' union all
select 'hs00004','dz002',2012001,'未','XX'
go
;with t
as(
select
a.id,
a.title,
b.numer
from
[书种表] a
inner join
[书册表] b
on
a.id=b.id
)
select
t.id,t.title,t.numer,
sum(case when s.name is not null then 1 else 0 end) times
from
t
left join
[借阅表] s
on
t.numer=s.numer
group by
t.id,t.title,t.numer
/*
id title numer times
----------- -------- ----------- -----------
1001 语文教材 2012001 2
1001 语文教材 2012002 1
1001 语文教材 2012003 0
1002 数学教材 2012004 0
1002 数学教材 2012005 1
(5 行受影响)
*/
--0表示没有借出