2014-03-12 94 views
0

我試圖將所有的信息數據分組/彙總在一起,但是我無法讓我知道它。包含左外連接的組列

是因爲我有內連接嗎?

SELECT DISTINCT jh."job-date",jh."company", jh."job-dept", jh."job-route", rc.COSTS, rh.SALES, rh.SALES - rc.COSTS as PROFIT 
FROM MSN.PUB."job-hdr" jh 

left outer join 
(select rh."rec-id", SUM(rh."base-sales-value") as SALES 
    from MSN.PUB."rec-chg" rh 
    group by rh."rec-id") rh 
on jh."job-id" = rh."rec-id" 

left outer join 
(select rc."rec-id", SUM(rc."base-cost-value") as COSTS 
    from MSN.PUB."rec-cost" rc 
    group by rc."rec-id") rc 
on jh."job-id" = rc."rec-id" 

WHERE 
    jh."job-status" <> 'D' and 
    jh."job-date" between '2012-04-01' and '2013-03-31' 
Group by jh."job-route", jh."company", jh."job-dept",jh."job-date", rc."COSTS", rh."SALES" 

這是我得到的結果。

工作至今公司工作,部門就業路線成本銷售利潤

2012-04-01 03 AII IBD 793.48 820.53 27.05

2012-04-01 03 AII ICH 20.87 43.35 22.48

2012-04-01 03 AII ICH 130.97 143.64 12.67

2012-04-01 03 AII ICH 291.52 363.63 72.11

2012-04-01 03 AII ICH 384.90 437.44 52.54

我需要他們總結,所以我沒有這麼多的數據行?

+0

您是否需要獲得總值,如一列或多列的總和或平均值? –

+0

我只需要每個日期,公司,Jobdept和工作路線的總成本,銷售和利潤 – user3411181

+0

此外,您沒有任何內部聯接 –

回答

1

你的問題是group by條款:

SELECT jh."job-date",jh."company", jh."job-dept", jh."job-route", 
     sum(rc.COSTS) as COSTS, 
     sum(rh.SALES) as SALES, sum(rh.SALES - rc.COSTS) as PROFIT 
FROM MSN.PUB."job-hdr" jh left outer join 
    (select rh."rec-id", SUM(rh."base-sales-value") as SALES 
     from MSN.PUB."rec-chg" rh 
     group by rh."rec-id" 
    ) rh 
    on jh."job-id" = rh."rec-id" left outer join 
    (select rc."rec-id", SUM(rc."base-cost-value") as COSTS 
     from MSN.PUB."rec-cost" rc 
     group by rc."rec-id" 
    ) rc 
    on jh."job-id" = rc."rec-id" 
WHERE jh."job-status" <> 'D' and 
     jh."job-date" between '2012-04-01' and '2013-03-31' 
Group by jh."job-route", jh."company", jh."job-dept", jh."job-date"; 

我刪除從group byCOSTSSALES並在select添加聚合函數。

+0

這是非常棒的工作,非常完美。 – user3411181