1

我想从 3 个不同的表中获取特定值。每个表具有相同的结构,但包含一年中不同时期的数据。

Temp_Table_Jun (Contains data for June month)
---------------
CustNo    CustName  Revenue
1000      John      5.55   

同样,我还有两张桌子

  • Temp_table_Apr
  • Temp_table_May

现在我运行一个查询

select sum(Revenue)Rev_June from Temp_Table_Jun where CustNo='1000' 

得到六月的结果。现在我的问题是我想在一个查询中获取整个月的收入详细信息。

我需要类似的东西,(这是错误的,不起作用)

select Rev_June,Rev_Apr,Rev_May,((Rev_June+Rev_Apr+Rev_May)/3)Avg_3_Mon from 
(
        select sum(Revenue)Rev_June from Temp_Table_Jun where CustNo='1000',
        select sum(Revenue)Rev_Apr from Temp_Table_Apr where CustNo='1000',
        select sum(Revenue)Rev_May from Temp_Table_May where CustNo='1000'   

)

如何做到这一点?我正在使用 Oracle 10g。

4

3 回答 3

5

要获取数据,您可以通过以下方式进行。Oracle 10g 没有,PIVOT但您可以使用CASE语句来复制功能:

SELECT sum(case when month = 'June' then Rev END) June
  , sum(case when month = 'May' then Rev END) May
  , sum(case when month = 'April' then Rev END) April
  , avg(Rev) as Average
FROM
(
  SELECT sum(revenue) Rev, 'June' as Month from rev_june where cust_no = '1000'
  union all
  SELECT sum(revenue) Rev, 'April' from rev_apr where cust_no = '1000'
  union all
  SELECT sum(revenue) Rev, 'May' from rev_may where cust_no = '1000'
) x

请参阅带有演示的 SQL Fiddle

或者您可以执行以下操作:

SELECT June, April, May, (June + April + May)/3 as Average
FROM
(
  select 
    (SELECT sum(revenue) from rev_june where cust_no = '1000') as June
  , (SELECT sum(revenue) from rev_apr where cust_no = '1000') as April
  , (SELECT sum(revenue) from rev_may where cust_no = '1000') as May
  from dual
) x

请参阅带有演示的 SQL Fiddle

于 2012-07-29T16:33:41.493 回答
3

以下可能有效:

select Rev_June, Rev_Apr, Rev_May,
    (Rev_June + Rev_Apr + Rev_May) / 3 Avg_3_Mon
from (
    (select sum(Revenue) from Temp_Table_Jun where CustNo='1000') as Rev_June,
    (select sum(Revenue) from Temp_Table_Apr where CustNo='1000') as Rev_Apr,
    (select sum(Revenue) from Temp_Table_May where CustNo='1000') as Rev_May
    from dual
)
于 2012-07-29T15:14:03.837 回答
1

我不知道它是否适用于 Oracle 10g,但大致如下所示的 UNION 查询通常适用于我使用过的数据库:

select sum(Revenue) Rev_June from Temp_Table_Jun where CustNo='1000'
UNION
select sum(Revenue) Rev_Apr from Temp_Table_Apr where CustNo='1000'
UNION
select sum(Revenue) Rev_May from Temp_Table_May where CustNo='1000'

我对标点符号不是很清楚——你需要在结尾处加分号吗?- 但这可能会让你开始。

我想我会稍有不同,因为每个查询必须具有相同的结构才能使 UNION 查询工作:

select sum(Revenue) Revenue_Sum, 'Jun' Month from Temp_Table_Jun where CustNo='1000'
UNION
select sum(Revenue) Revenue_Sum, 'Apr' Month from Temp_Table_Apr where CustNo='1000'
UNION
select sum(Revenue) Revenue_Sum, 'May' Month from Temp_Table_May where CustNo='1000'

现在,这并不能完全得到平均总和和您正在寻找的 3 列,但也许您可以使用类似 UNION 查询的内容创建一个 VIEW,然后在该 VIEW 上使用 GROUP BY 查询来聚合数据。

于 2012-07-29T14:59:02.067 回答