2013-10-13 68 views
0

我有一個包含子查詢並僅輸出12行數據的Postgres查詢,完全如何我希望它看起來。這些行中的每一行代表數據庫中所有年份的數據的月平均值,每個月一行。 查詢:Postgres根據年數返回多個相同的結果

SELECT 
    to_char(to_timestamp(to_char(subquery2.month, '999'), 'MM'), 'Mon') AS Month, 
    subquery2.month AS Month_num, 
    round(AVG(subquery2.all_use_tot), 2) AS Average_Withdrawals, 
    round(AVG(subquery2.all_cu_tot), 2) AS Average_Consumptive_Use 
FROM 
(SELECT 
    subquery1.month, 
    subquery1.year, 
    sum(subquery1.liv_tot) AS all_use_tot, 
    sum(subquery1.CU_total) AS all_cu_tot 
FROM 
    (SELECT 
     EXTRACT('Month' FROM withdrawals.begintime) AS month, 
     EXTRACT(YEAR FROM withdrawals.begintime)::int AS year, 
     tdx_ic_use_type.use_type_code AS Use_type, 
     sum(withdrawals.withdrawalvalue_mgd) AS liv_tot, 
     (tdx_ic_use_type.cufactor)*(sum(withdrawals.withdrawalvalue_mgd)) AS CU_total 
    FROM 
     medford.tdx_ic_use_type, 
     medford.withdrawalsites 
     JOIN medford.subshed2 ON ST_Contains(medford.subshed2.the_geom, medford.withdrawalsites.the_geom) 
     JOIN medford.withdrawals ON medford.withdrawals.ic_site_id = medford.withdrawalsites.ic_site_id 
    WHERE 
     subshed2.id = '${param.shed_id}' AND 
     withdrawalsites.ic_pr_use_type_id = tdx_ic_use_type.use_type_code AND 
     withdrawals.intervalcodes_id = 2 

    GROUP BY 
     year, 
     extract('Month' from withdrawals.begintime), 
     tdx_ic_use_type.cufactor, 
     Use_type 
    ORDER BY 
     year, extract('Month' from withdrawals.begintime) ASC 
     ) AS subquery1 
GROUP BY 
    subquery1.year, 
    subquery1.month 
) AS subquery2 
GROUP BY 
    subquery2.month 
ORDER BY 
    subquery2.month 

輸出的樣子:

"Jan" 1 1426.50 472.65 
"Feb" 2 1449.00 482.10 
"Mar" 3 1459.50 485.55 
"Apr" 4 1470.00 489.00 
"May" 5 1480.50 492.45 
"Jun" 6 1491.00 495.90 
"Jul" 7 1489.50 493.35 
"Aug" 8 1512.00 502.80 
"Sep" 9 1510.50 500.25 
"Oct" 10 1533.00 509.70 
"Nov" 11 1543.50 513.15 
"Dec" 12 1542.00 510.60 

月份列,我從數據庫中的日期時間列提取。我正在使用這個查詢的結果並將其存儲在一個數組中,但是我想重複一遍表中存在的每一年的這些確切結果。因此,如果數據庫中有2年的數據,則應該有24個輸出行,或者相同行中的12個重複兩次。如果數據庫中有3年的數據,應該有36個輸出行,或者12個相同的行重複3次。 如何在我的查詢中完成此操作?有沒有辦法根據列中的值循環查詢(即日期時間字段中存在的年數?)

回答

2

您應該在查詢中將group by month更改爲group by year, month。 (但是這會給你只會導致哪裏有特定月份的數據。)

對於迭代通過幾個月:

select a::date 
from generate_series(
    '2011-06-01'::date, 
    '2012-06-01', 
    '1 month' 
) s(a) 

(在此基礎上:Writing a function in SQL to loop through a date range in a UDF

+0

感謝您的想法。我用實際查詢更新了我的問題。我以幾種不同的方式嘗試了你的建議,但是價值觀在不同年份有所變化,所以相同的12個月的數據集並沒有重複,而是在變化。有什麼方法可以根據列中的值循環查詢嗎? – Jan

+0

我添加了一個例子來生成月份。你應該加入這個結果集。 –

相關問題