我有2个表,其结构如下:
tblBookMst
Id bk_isbn bk_title bk_author
----------------------------------------------------
1 ISBN_001 ABC Book AA
2 ISBN_002 DEF Book BB
3 ISBN_003 GHI Book CC
4 ISBN_004 JKL Book DD
和
tblBookId
b_id id lib_id inv_stat
----------------------------------------------------
1 1 BK/LIB/01 1
2 1 BK/LIB/02 2
3 1 BK/LIB/03 2
4 2 BK/LIB/04 1
5 2 BK/LIB/05 1
6 3 BK/LIB/06 1
(' inv_stat'传说:1 =>有库存& 2 =>在流通中) 使用上面的两个表,我想写一个查询,它将给我输出如下所示
bk_title bk_author tot_copies in_stock in_circulation
ABC Book AA 3 1 2
DEF Book BB 2 2 0
GHI Book CC 1 1 0
到目前为止,我一直无法弄清楚如何计算' in_stock' &安培; ' in_circulation'。我正在使用下面提到的SQL查询。
SELECT a.id,a.bk_title,a.bk_author,count(b.lib_id) as tot_copies
FROM tblBookMst a
JOIN tblBookId b ON a.id = b.id
GROUP BY a.id,a.bk_title,a.bk_author
ORDER BY a.bk_title
我希望你理解我的问题。请举例说明
答案 0 :(得分:2)
你很亲密!你只需要一些Case Statements:
SELECT a.id,
a.bk_title,
a.bk_author,
count(b.lib_id) as tot_copies
SUM(CASE WHEN b.inv_stat = 1 THEN 1 ELSE 0 END) as in_stock,
SUM(CASE WHEN b.inv_stat = 2 THEN 1 ELSE 0 END) as in_circulation
FROM tblBookMst a
JOIN tblBookId b ON a.id = b.id
GROUP BY a.id,a.bk_title,a.bk_author
ORDER BY a.bk_title