2016-06-21 8 views
0

Ich habe 2 Tabellen, deren Struktur ist wie folgt:Können Inventar aktuellen Bestandsberechnung herauszufinden

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 

und

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' Legenden: 1 => Im Lager & 2 = > In Circulation) die über 2 Tabellen verwenden, möchte ich eine Abfrage schreiben, die mir Ausgabe unter

wie gezeigt geben
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 

Bis jetzt konnte ich nicht herausfinden, wie man den "in_stock" & 'in_circulation' berechnet. Ich verwende die unten erwähnte SQL-Abfrage.

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 

Ich hoffe, dass Sie meine mögliche Frage Beratung mit Beispiel

Antwort

2

Sie sind nah verstehen! Sie brauchen nur einige 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 
+0

Dank @JNevill Sie sind toll !. –