簡體   English   中英

在PostgreSQL中按年份分組

[英]group by year month in postgresql

 customer      Date      location

     1         25Jan2018     texas

     2         15Jan2018     texas

     3         12Feb2018     Boston

     4         19Mar2017     Boston.

我正在嘗試按日期列的Yearmon找出客戶組的數量。日期列是文本數據類型

例如:在jan2018中,計數為2

您不應該將日期存儲在文本列中...

select substring(Date, length(Date)-6), count(*)
from tablename
group by substring(Date, length(Date)-6)

我將執行以下操作:

SELECT
  date_part('year', formattedDate) as Year
 ,date_part('month', formattedDate) as Month
 ,count(*) as CustomerCountByYearMonth
FROM
 (SELECT to_date(Date,'DDMonYYYY') as formattedDate from <table>) as tbl1
GROUP BY
  date_part('year', formattedDate)
 ,date_part('month', formattedDate)

日期的任何其他格式都可以在內部查詢上進行,以進行調整,以防萬一需要填充一些個位數的天,或者一個月中的四個字母而不是三個字母。

通過轉換為日期類型,您可以按日期類型正確排序,而不要按字母順序排序。

可選:

SELECT
  Year
 ,Month
 ,count(*) as CustomerCountByYearMonth
FROM
 (SELECT
   date_part('year', to_date(Date,'DDMonYYYY')) as Year
  ,date_part('month', to_date(Date,'DDMonYYYY')) as Month
 FROM <table>) as tbl1
GROUP BY
  Year
 ,Month

我以為@Jarlh問了一個好問題-像1月1日這樣的日期呢? 是2019年1月1日還是2019年1月1日? 如果可以,則正則表達式可能會起作用。

select
  substring (date from '\d+(\D{3}\d{4})') as month,
  count (distinct customer)
from t
group by month

“與眾不同的客戶”還假設您可能在同一個月內列出了同一位客戶,但是您只想計算一次即可。 如果不是這種情況,請刪除“與眾不同”。

並且,如果您希望以日期格式輸出:

select
  to_date (substring (date from '\d+(\D{3}\d{4})'), 'monyyyy') as month,
  count (distinct customer)
from t
group by month

如果它是日期列,則可以截斷日期:

select date_trunc('month', date) as yyyymm, count(*)
from t
group by yyyymm
order by yyyymm;

我真的讀過,類型是date 對於字符串,只需使用字符串函數:

select substr(date, 3, 7) as mmmyyyy, count(*)
from t
group by mmmyyyy;

不幸的是,在這種情況下無法訂購。 您實際上應該使用適當的類型存儲日期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM