2016-10-03 63 views
0

我的數據庫:加入問題上的SQL請求

TB_DW_VAB_FLIGHT : ID_TEC_FLIGHT 
    TB_DW_VAB_SALES : QUANTITY, TRANSACTION_NUMBER, UNIT_SALES_PRICE 

我想有4列作爲結果的表:CA,QTE,NB_TRANSACTION和NB_VOLS在同一個月。 (N-1)

我試着像這樣的SQL請求:

SELECT 
    sum(QUANTITY*UNIT_SALES_PRICE) as CA, 
    sum(QUANTITY) as QTE, 
    count(distinct TRANSACTION_NUMBER) as NB_TRANSACTION, 
    count(distinct ID_TEC_FLIGHT) as NB_VOLS 
FROM TB_DW_VAB_SALES, TB_DW_VAB_FLIGHT 
where to_char(TB_DW_VAB_SALES.FLIGHT_DATE,'MM')=to_char(current_date,'MM')-1 and to_char(TB_DW_VAB_SALES.FLIGHT_DATE,'YYYY')=to_char(current_date,'YYYY') and SALES_TYPE='SALES' 
and to_char(TB_DW_VAB_FLIGHT.FLIGHT_DATE,'MM')=to_char(current_date,'MM')-1 and to_char(TB_DW_VAB_FLIGHT.FLIGHT_DATE,'YYYY')=to_char(current_date,'YYYY'); 

但甲骨文能不能給我一個答案。

非常感謝您的幫助。

+0

有TB_DW_VAB_FLIGHT和TB_DW_VAB_SALES之間沒有任何關係。 ID_TEC_FLIGHT完全告訴你什麼? – JohnHC

+0

這兩張表之間沒有任何關係,我只是想顯示我的表中ID號(ID_TEC_FLIGHT)的計數的航班號TB_DW_VAB_FLIGHT – devicz

回答

0

嘗試

with CTE1 as 
(
select to_char(FLIGHT_DATE, 'MM-YYYY') as PERIOD, 
     sum(QUANTITY*UNIT_SALES_PRICE) as CA, 
     sum(QUANTITY) as QTE, 
     count(distinct TRANSACTION_NUMBER) as NB_TRANSACTION 
from TB_DW_VAB_SALES 
where SALES_TYPE = 'SALES' 
group by to_char(FLIGHT_DATE, 'MM-YYYY') 
) 
, CTE2 as 
(
select count(distinct ID_TEC_FLIGHT) as NB_VOLS, 
     to_char(FLIGHT_DATE, 'MM-YYYY') as PERIOD 
from TB_DW_VAB_FLIGHT 
group by to_char(FLIGHT_DATE, 'MM-YYYY') 
) 
select CTE1.CA, 
     CTE1.QTE, 
     CTE1.NB_TRANSACTION, 
     CTE2.NB_VOLS 
from CTE1 
inner join CTE2 on CTE1.PERIOD = CTE2.PERIOD 
where CTE1.PERIOD = to_char(add_Months(sysdate,-1),'MM-YYYY') 

,或者如果CTE的軟件中的不可用:

select CTE1.CA, 
     CTE1.QTE, 
     CTE1.NB_TRANSACTION, 
     CTE2.NB_VOLS 
from 
(
select to_char(FLIGHT_DATE, 'MM-YYYY') as PERIOD, 
     sum(QUANTITY*UNIT_SALES_PRICE) as CA, 
     sum(QUANTITY) as QTE, 
     count(distinct TRANSACTION_NUMBER) as NB_TRANSACTION 
from TB_DW_VAB_SALES 
where SALES_TYPE = 'SALES' 
group by to_char(FLIGHT_DATE, 'MM-YYYY') 
) CTE1 
inner join 
(
select count(distinct ID_TEC_FLIGHT) as NB_VOLS, 
     to_char(FLIGHT_DATE, 'MM-YYYY') as PERIOD 
from TB_DW_VAB_FLIGHT 
group by to_char(FLIGHT_DATE, 'MM-YYYY') 
) CTE2 
    on CTE1.PERIOD = CTE2.PERIOD 
where CTE1.PERIOD = to_char(add_Months(sysdate,-1),'MM-YYYY') 
+0

@AlexPoole他自從更新了原始帖子後...現在編輯 – JohnHC

+0

有用 !萬分感謝 !! – devicz

+0

嗨回來, 這個請求在Oracle中工作正常,但JasperSoft不想構建「with」。傳統SQL中有可能獲得類似的請求嗎? – devicz