2012-12-21 64 views
0

我不知道是否有問題,這樣在那裏已經,找不到我的解決方案,很抱歉,如果這是一個重複: 我有日期的表:號碼,集團的PostgreSQL的選擇總和日期

|date (date)| tax (numeric) | (stuff in brackets is the type) 
    |2012-12-12 | 5.00   | 
    |2012-12-12 | 10.00   | 
    |2012-12-13 | 2.00   | 

我想我的輸出看起來像這樣:

|date (date)| tax (numeric) | (stuff in brackets is the type) 
    |2012-12-12 | 15.00   | 
    |2012-12-13 | 2.00   | 

我想這樣做的CTE類型的查詢,因爲在DATEBASE,我存儲的東西因爲沒有時區的日期時間,和一堆稅 這是我的查詢開始:

with date_select as 
(
select CAST(r.datetime as DATE), sum(r.tax) as tax 
from suezensalon.receipt r 
where r.datetime between '2012-12-12 00:00:00' and '2012-12-18 23:59:59' 
group by r.datetime 
order by r.datetime 
) 

這給了我頂面的表格。做這個的最好方式是什麼?是通過'平均日期'?

+0

在你查詢你有日期時間,但在樣本數據的日期。是對的嗎? – opensourcegeek

+0

是的,它是正確的,我把它作爲cte中的日期。 – akwarywo

+0

你不應該當你真的想與開放或半開放間隔作品之間使用,只能用封閉間隔之間使用。如果您的時間間隔未關閉,請對端點使用單獨的檢查。 –

回答

1

這是結束了工作:

with date_select as 
(
select CAST(r.datetime as DATE), sum(r.tax) as tax 
from suezensalon.receipt r 
where r.datetime between '2012-12-12 00:00:00' and '2012-12-18 23:59:59' 
group by r.datetime 
order by r.datetime 
) 
select extract(Month from datetime) || '-' || extract(Day from datetime) || '-' || extract(Year from datetime) as Date, sum(tax) 
from date_select 
group by Date 
order by Date; 
0

我認爲最簡單的選擇,並且最有可能在索引的存在,表現良好,將是這樣的:

SELECT 
    datetime::date as "Date", 
    sum(tax) 
    FROM suezensalon.receipt 
    WHERE datetime >= '2012-12-12 00:00:00' 
    AND datetime < '2012-12-19 00:00:00' 
    GROUP BY datetime::date 
    ORDER BY "Date";