2017-07-31 94 views
0

這裏價值觀是什麼,我想實現一個例子:SQL GROUPBY在排序時間序列

表A:

| type | message |   createdAt   | 
|:----------:|:---------:|:--------------------------:| 
| create  | awesome | 2017-07-21 11:20:35.147629 |  
| create  | hello | 2017-07-21 11:20:35.147629 |  
| create  | good  | 2017-07-22 10:20:34.123331 |  
| upload  | nope  | 2017-07-22 11:28:08.815828 |  
| create  | test  | 2017-07-22 11:29:35.147629 |  
| create  | hello | 2017-07-22 12:20:35.147629 | 

所需的輸出:

| type | new_message |  new_createdAt  | 
|:------:|:------------:|:--------------------------:| 
| create |  3  | 2017-07-22 10:20:34.123331 | 
| upload |  nope  | 2017-07-22 11:28:08.815828 | 
| create |  2  | 2017-07-22 12:20:35.147629 | 

的SQL語句如果它們的順序爲createdAt,則應該組合類似的type。如果一個序列中的相似值type的數量大於1,那麼new_message是其他的new_messagemessage相同(這個if-else子句不是最重要的特徵,只是給出count的語句也可以)。

謝謝。

UPDATE

是否有可能在時間序列中增加的另一個因素,分組只有在最低和最高createdAt之間的差別是說十

例如如果我選擇X = 24個小時,輸出表A將變更爲:

| type | new_message |  new_createdAt  | 
|:------:|:------------:|:--------------------------:| 
| create |  2  | 2017-07-21 11:20:35.147629 | 
| create |  good  | 2017-07-22 10:20:34.123331 | 
| upload |  nope  | 2017-07-22 11:28:08.815828 | 
| create |  2  | 2017-07-22 12:20:35.147629 | 

有什麼辦法沒有JOIN這樣做。

+0

使用[this](https://gis.stackexchange)解決時間間隔問題(** UPDATE **部分)。 com/a/127874) –

回答

2

您可以使用ROW_NUMBER分野:

WITH CteRn AS(
    SELECT *, 
     ROW_NUMBER() OVER(ORDER BY createdAt) 
      - ROW_NUMBER() OVER(PARTITION BY type ORDER BY createdAt) AS rn 
    FROM Tbl 
) 
SELECT 
    type, 
    CASE 
     WHEN COUNT(*) > 1 THEN CAST(COUNT(*) AS VARCHAR(30)) 
     ELSE MAX(cte.message) 
    END AS message, 
    MAX(cte.createdAt) AS createdAt 
FROM CteRn cte 
GROUP BY cte.type, cte.rn 
ORDER BY MAX(cte.createdAt); 

ONLINE DEMO

+0

謝謝,多一點解釋會有所幫助。 –

1

我會做到這一點使用行號,然後聚集的差異,用一個單一的子查詢:

select type, 
     (case when count(*) = 1 then max(message) else count(*)::text end) as message, 
     min(created_at) as new_createdAt 
from (select t.*, 
      row_number() over (order by createdAt) as seqnum_c, 
      row_number() over (partition by type order by createdAt) as seqnum_tc 
     from t 
    ) t 
group by type, (seqnum_c - seqnum_tc) 
order by new_createdAt;