2015-02-10 72 views
0

我試圖得到一個單一的一個內的兩個請求的結果,這兩個以下要求功能齊全,他們每個人都得到一個表格有兩列:替補2 SQL/ORACLE請求只由一個請求

SELECT patron.last_name, COUNT(*) AS **pret** 
FROM circ_transaction_log INNER JOIN patron ON  circ_transaction_log.patron_id=patron.patron_id 
AND **circ_transaction_log.transaction_type<5** 
AND patron.college_or_school = 'High School' 
GROUP BY patron.last_name; 

姓氏 | pret
________________
steven grelle | 552
michelle vins | 122 ...

_________________________ OR _________________________

SELECT patron.last_name, COUNT(*) AS **resa** 
FROM circ_transaction_log INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id 
AND **circ_transaction_log.transaction_type BETWEEN 5 AND 10** 
AND patron.college_or_school = 'High School' 
GROUP BY patron.last_name; 

姓氏 | resa
________________
steven grelle | 12
michelle vins | 8
...

我希望得到的結果是有點像這樣:

姓氏 | resa | pret
_______________________________
steven grelle | 552 | 12
michelle vins | 122 | 8
...

但我認爲困難是,我請求同一個表兩次枝條計數(表CIRC_TRANSACTION_LOG)和任何我想是或者錯誤或不提前工作

謝謝您回覆

問候, Nickk

+0

MySQL和SQL Server和Oracle?你真的使用這3個? – jarlh 2015-02-10 12:10:57

+0

在last_name上加入你的兩個請求(查詢) – 2015-02-10 12:11:22

回答

1

你這樣的事情後,則:

SELECT p.last_name, 
     COUNT(case when ctl.transaction_type < 5 then 1 end) AS pret, 
     count(case when ctl.transaction_type between 5 and 10 then 1 end) as resa 
FROM  circ_transaction_log ctl 
     INNER JOIN patron p ON (ctl.patron_id = p.patron_id) 
AND  ctl.transaction_type <= 10 -- possibly not required if transaction_type is always <= 10 
AND  p.college_or_school = 'High School' 
GROUP BY p.last_name; 

注意。未經測試,因爲您沒有爲您的表格提供任何樣本數據。

+1

非常感謝你,這個工作很好,我實際上試着按照你的條件來計算,但是我忘記了合成器中的「case」...太感謝了 :) – Nickk 2015-02-10 12:25:53

0

我更喜歡這種方法。如果該行與您的條件匹配,則將1放在列中,如果不匹配,則將其設置爲0.然後,當您將所有值相加時,它會爲您提供匹配的行數。這允許您爲不同的條件創建不同的總和。

SELECT 
    PatronCounts.last_name, 
    SUM(PatronCounts.Pret) Pret, 
    SUM(PatronCounts.Resa) Resa 
FROM 
(SELECT 
    patron.last_name, 
    CASE WHEN circ_transaction_log.transaction_type < 5 THEN 1 ELSE 0 END AS Pret, 
    CASE WHEN circ_transaction_log.transaction_type BETWEEN 5 AND 10 THEN 1 ELSE 0 END AS Resa, 
FROM 
    circ_transaction_log 
    INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id 
WHERE 
    patron.college_or_school = 'High School' 
GROUP BY 
    patron.last_name) PatronCounts 
0

你可以結合你的查詢qith一個全外使用(姓氏)加入你的結果表。這應該會產生預期的結果。試圖創建查詢...

Select * from 
(SELECT patron.last_name, COUNT(*) AS pret 
FROM circ_transaction_log INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id 
AND circ_transaction_log.transaction_type<5 
AND patron.college_or_school = 'High School' 
GROUP BY patron.last_name) 
FULL OUTER JOIN 
(SELECT patron.last_name, COUNT(*) AS resa 
FROM circ_transaction_log INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id 
AND circ_transaction_log.transaction_type BETWEEN 5 AND 10 
AND patron.college_or_school = 'High School' 
GROUP BY patron.last_name) 
USING (last_name) 

;