加入几个选择

时间:2011-07-20 15:14:42

标签: sql oracle select

我有这样的假表:

data:
    id  type    month   value
    1   1       1       10
    2   1       2       20
    3   1       3       30
    4   2       1       40
    5   2       2       50
    6   2       3       60
    7   3       1       70
    8   3       2       80
    9   3       3       90
    10  4       1       100
    11  4       2       110
    12  4       3       120

type:
    id  name
    1   A
    2   B
    3   C
    4   D

What I want:
    month   valueA  valueB  valueC  valueD
    1       10      40      70      100
    2       20      50      80      110
    3       30      60      90      120

如何进行此查询? 我正在使用Oracle 10g。

2 个答案:

答案 0 :(得分:5)

看起来你想要一个相对简单的数据枢轴。如果你使用11g,你可以使用更优雅的PIVOT功能。但是在10g中,你仍然可以做这样的事情

SQL> ed
Wrote file afiedt.buf

  1  with data as (
  2    select 1 id, 1 type, 1 month, 10 value from dual union all
  3    select 2,1,2,20 from dual union all
  4    select 3,1,3,30 from dual union all
  5    select 4,2,1,40 from dual union all
  6    select 5,2,2,50 from dual union all
  7    select 6,2,3,60 from dual union all
  8    select 7,3,1,70 from dual union all
  9    select 8,3,2,80 from dual union all
 10    select 9,3,3,90 from dual union all
 11    select 10,4,1,100 from dual union all
 12    select 11,4,2,110 from dual union all
 13    select 12,4,3,120 from dual
 14  ),
 15  type as (
 16    select 1 id, 'A' name from dual union all
 17    select 2,'B' from dual union all
 18    select 3,'C' from dual union all
 19    select 4,'D' from dual)
 20  select d.month,
 21         max(case when t.name = 'A' then d.value else null end) valueA,
 22         max(case when t.name = 'B' then d.value else null end) valueB,
 23         max(case when t.name = 'C' then d.value else null end) valueC,
 24         max(case when t.name = 'D' then d.value else null end) valueD
 25    from data d,
 26         type t
 27   where d.type = t.id
 28*  group by d.month
SQL> /

     MONTH     VALUEA     VALUEB     VALUEC     VALUED
---------- ---------- ---------- ---------- ----------
         1         10         40         70        100
         2         20         50         80        110
         3         30         60         90        120

答案 1 :(得分:1)

就像这样...

SELECT month
      ,SUM(valueA) AS valueA
      ,SUM(valueB) AS valueB
      ,SUM(valueC) AS valueC
      ,SUM(valueD) AS valueD
FROM (
SELECT month , DECODE(type,1,value,0) valueA
             , DECODE(type,2,value,0) valueB
             , DECODE(type,3,value,0) valueC
             , DECODE(type,4,value,0) valueD
FROM DATA)
GROUP BY month
order by month