0
我有一張表,其中一列應該根據另一列挑選數據。這可能是最好的展示。從不同標準的列中選擇一個表 - SQL Oracle
我的DB:
預期結果:
所以我試圖用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'
什麼是一個正確的方法來做到這一點..?
編輯/ UPDATE:由於我的問題已經被標記爲可能由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
它被稱爲_pivot_。使用術語「oracle」和「pivot」搜索SO上的一些問題 –
[Oracle SQL數據透視查詢](http://stackoverflow.com/questions/4841718/oracle-sql-pivot-query) –
@FlorinGhita謝謝徵求意見。但是,由於某些原因,用我的數據替換該數據,導致錯誤.. '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 budget t' –