2014-06-10 148 views
1

我需要對兩個數據集中的變量進行求和並將其加入。我想在一個SQL語句中執行此操作,但它是一對多連接。我有興趣瞭解是否可以使用SELECT語句創建摘要變量,因爲缺少更好的描述。使用Proc創建彙總變量SQL

下面的代碼錯誤地計算了HOURS的摘要變量,因爲INTERVAL中每個名稱/日期只有一條記錄,但詳細信息中每個名稱/日期有多個記錄。

我當然可以編寫多個步驟來完成這個任務,但是想看看它是否可以在一個SQL步驟中完成。由於

示例代碼:

data Detail; 
Length Name CallType $25; 
input date mmddyy10. name $ calltype $ count; 
Format date mmddyy10.; 
datalines; 
05/01/2014 John Order 5 
05/01/2014 John Complaint 6 
05/01/2014 Mary Order 7 
05/01/2014 Mary Complaint 8 
05/01/2014 Joe Order 4 
05/01/2014 Joe Complaint 2 
05/01/2014 Joe Internal 2 
05/02/2014 John Order 6 
05/02/2014 John Complaint 4 
05/02/2014 Mary Order 9 
05/02/2014 Mary Complaint 7 
05/02/2014 Joe Order 3 
05/02/2014 Joe Complaint 1 
05/02/2014 Joe Internal 3 
; 

data Interval; 
Length Name $25; 
input date mmddyy10. name $ hours; 
Format date mmddyy10.; 
datalines; 
05/01/2014 John 8 
05/01/2014 Mary 6 
05/01/2014 Joe 4 
05/02/2014 John 8 
05/02/2014 Mary 6 
05/02/2014 Joe 4 
; 

PROC SQL noprint feedback; 
CREATE TABLE SUMMARY AS 
SELECT 
    D.Name 
    , Sum(D.Count) as Count 
    , Sum(I.Hours) as Hours 
FROM Detail D, Interval I 
WHERE D.Name=I.Name and D.Date=I.Date 
GROUP BY D.Name 
ORDER BY D.Name; 
QUIT; 

回答

2

這工作,不應該是效率太低。我個人認爲最好的辦法是總結雙方合併之前單獨:

PROC SQL noprint feedback; 
CREATE TABLE SUMMARY AS 
SELECT 
    D.Name 
    , Sum(D.Count) as Count 
    , (SELECT sum(I.Hours) as Hours from Interval I WHERE D.Name=I.Name GROUP BY i.name) as Hours 
FROM Detail D 
GROUP BY D.Name 
ORDER BY D.Name 
; 
QUIT; 
+0

謝謝。因爲它更容易調試?代碼更清潔?或者你認爲它更有效率? –

+0

因此,在你的外部FROM語句中,你不做一個連接? –

+0

這只是GROUP BY語句中的拼寫錯誤嗎? –

2

羅伯特的解決方案工作正常,但是從條款移動子查詢時將改爲在選擇使用它們的,我得到更好更流暢。在兩個查詢中使用時,只執行一次結果,而選擇中的子查詢將爲每行執行一次。

proc sql; 
     create table summary as 
     select 
      d.name, 
      count, 
      hours 
     from 
      (select name, sum(count) as count from detail group by name) d inner join 
      (select name, sum(hours) as hours from interval group by name) i 
      on d.name = i.name 
     order by d.name 
    ; 
    quit; 
+0

是的,我其實更喜歡你的解決方案Laurent ...更容易閱讀,表現更好。 –