加入SQL请求的问题

时间:2016-10-03 15:16:56

标签: sql oracle

我的数据库:

  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');

但甲骨文不能给我一个答案。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分: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')