从具有不同标准的列中挑选到一个表 - SQL Oracle

时间:2015-10-13 10:35:16

标签: sql oracle

我有一个表,其中一列,应根据另一列选择数据。最好展示一下。

我的数据库:

enter image description here

预期结果:

enter image description here

所以我尝试用join来做,但它可能是错的,因为它全部来自一个表。我在这一点上陷入困​​境:

SELECT b1.area as line, b2.budget/12 as flow_MTD, b2.budget as flow_BUDGET,
b1.budget/12 as investment_products_MTD, b1.budget as 

investment_products_BUDGET,
b3.budget/12 as bonds_MTD, b3.budget as bonds_BUDGET,
b4.budget/12 as structure_MTD, b4.budget as structure_BUDGET    

    FROM budgets b1

    JOIN budgets b2 ON b1.area=b2.area

    JOIN budgets b3 ON b1.area=b3.area
    JOIN budgets b4 ON b1.area=b4.area

    where b1.limit = 'main'
    and b1.neighbourhood = 'alpha'
    and b2.neighbourhood = 'beta'

    and b3.neighbourhood = 'delta'
    and b4.neighbourhood = 'gamma'

这样做的正确方法是什么??

编辑/更新:由于我的问题已标记为Oracle SQL pivot query可能已解决 ..解决方案似乎不起作用,除非可以纠正:

SELECT SUM(CASE WHEN t.neighbourhood = 'alpha' THEN t.value ELSE 0 END) AS alpha,
       SUM(CASE WHEN t.neighbourhood = 'beta' THEN t.value ELSE 0 END) AS beta,
       SUM(CASE WHEN t.neighbourhood = 'delta' THEN t.value ELSE 0 END) AS delta,
       SUM(CASE WHEN t.neighbourhood = 'gamma' THEN t.value ELSE 0 END) AS gamma
  FROM budgets t

1 个答案:

答案 0 :(得分:0)

这就是你在寻找什么

SELECT b.area,
       v.total_alpha / 12 AS monthly_alpha,
       v.total_alpha,
       v.total_beta / 12 AS monthly_beta,
       v.total_beta,
       v.total_gamma / 12 AS monthly_gamma,
       v.total_gamma,
       v.total_delta / 12 AS monthly_delta,
       v.total_delta,
       v.total_alpha + v.total_beta + v.total_gamma + v.total_delta AS total
FROM (SELECT b.area,
             SUM(DECODE(b.neighbourhood, 'alpha', b.budget, 0)) AS total_alpha,
             SUM(DECODE(b.neighbourhood, 'beta', b.budget, 0)) AS total_beta,
             SUM(DECODE(b.neighbourhood, 'gamma', b.budget, 0)) AS total_gamma,
             SUM(DECODE(b.neighbourhood, 'delta', b.budget, 0)) AS total_delta
      FROM budgets b
      GROUP BY b.area
     ) v