簡體   English   中英

如何將日期分組為月份並在分組后添加新列

[英]How to group dates into month and add a new column after grouping

這是我與 SQL 在一起的第 7 天。我有一個日期列表,我想根據月份對它們進行分組。 這是桌子。 它只有一列,即dateOfService 格式為YYYY-MM-DD

+---------------+
| dateOfService |
+---------------+
| 2020-05-28    |
| 2020-05-29    |
| 2020-05-30    |
| 2020-06-03    |
| 2020-06-05    |
| 2020-07-21    |
| 2020-07-23    |
| 2020-07-25    |
| 2020-07-28    |
+---------------+

忽略DD部分,我想將這些日期分組如下。 就像是:

+---------------+---------------+
| monthOfService| dateOfService |
+---------------+---------------+
|    2020-05    |  2020-05-28   |
|               |  2020-05-29   |
|               |  2020-05-30   |
|---------------|---------------|
|    2020-06    |  2020-06-03   |
|               |  2020-06-05   |
|---------------|---------------|
|    2020-07    |  2020-07-21   |
|               |  2020-07-23   |
|               |  2020-07-25   |
|               |  2020-07-28   |
+---------------+---------------+

我必須從dateOfService本身創建monthOfService 如果monthOfService中的行重復,沒關系。 請告訴我方法。

使用ROW_NUMBER() window function:

select case when rn = 1 then date_format(dateOfService, '%Y-%m') end monthOfService,
       dateOfService
from (       
  select *, 
    row_number() over (partition by date_format(dateOfService, '%Y-%m') order by dateOfService) rn
  from tablename
) t
order by dateOfService

請參閱演示
結果:

> monthOfService | dateOfService
> :------------- | :------------
> 2020-05        | 2020-05-28   
> null           | 2020-05-29   
> null           | 2020-05-30   
> 2020-06        | 2020-06-03   
> null           | 2020-06-05   
> 2020-07        | 2020-07-21   
> null           | 2020-07-23   
> null           | 2020-07-25   
> null           | 2020-07-28  

如果你想重復monthOfService的值,那么:

select date_format(dateOfService, '%Y-%m') monthOfService,
       dateOfService
from tablename
order by dateOfService

請參閱演示
結果:

> monthOfService | dateOfService
> :------------- | :------------
> 2020-05        | 2020-05-28   
> 2020-05        | 2020-05-29   
> 2020-05        | 2020-05-30   
> 2020-06        | 2020-06-03   
> 2020-06        | 2020-06-05   
> 2020-07        | 2020-07-21   
> 2020-07        | 2020-07-23   
> 2020-07        | 2020-07-25   
> 2020-07        | 2020-07-28  

您可以使用group_concat()

select extract(year_month from date) as yyyymm, group_concat(date)
from t
group by yyyymm;

這使用列表的默認逗號分隔符。 這比在 SQL 查詢中使用新行更常見。

暫無
暫無

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

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