簡體   English   中英

SQL - 將記錄組合在一起

[英]SQL - Group records together

目前我有一個包含以下值的表:

  some-id   timestamp   modified_by   other_info
 --------- ----------- ------------- ------------
      1       12:45      person_1        misc
      1       12:50      person_5       stuff
      2        3:13      robot_1        things
      2        3:15      random_1       more
      3       11:33
      3       11:50

我希望生成的SELECT返回以下內容:

  some-id    duration     start_person    end_person     other_info
 --------- ------------- -------------- -------------- --------------
      1         5           person_1       person_5        misc
      2         2            robot_1       random_1
      3         17         

例如。 timestamp由重復的some_id分組。 我想顯示some_id的持續時間以及與相應時間戳鏈接的用戶的值。

我能夠創建具有持續時間的表,但試圖弄清楚如何包含start_personend_person

SELECT some-id, TIMESTAMP_DIFF(MAX(timestamp), MIN(timestamp), MILLISECOND) as duration
FROM t
GROUP BY some-id

如果我不能編寫查詢,我總是只使用 RowNumber:

    select 
      some_id,
      TIMEDIFF(MAX(timestamp), MIN(timestamp)) as duration, 
      max(IF(rownum = 1, modified_by, null)) as start_person,
      max(IF(rownum = 2, modified_by, null)) as end_person,
      max(if(rownum = 1 /*and some_id != 2*/, other_info, null)) as other_info
    from (
      select *, row_number() over(partition by some_id order by modified_by) as rownum
      from table_name
    ) t
    group by some_id

您可以找到持續時間,然后將原始表重新加入其中:

with cte(id, m1, m2) as (
    select t.id, max(t.timestamp), min(t.timestamp) from tbl t group by t.id
)
select c.id, timediff(concat(date(now()), ' ', c.m1, ':00'), concat(date(now()),' ',c.m2,':00')), t1.modified_by, t2.modified_by, t1.other_info 
from cte c left join tbl t1 on c.m2 = t1.timestamp left join tbl t2 on c.m1 = t2.timestamp group by c.id, timediff(concat(date(now()), ' ', c.m1, ':00'), concat(date(now()),' ',c.m2,':00')), t1.modified_by, t2.modified_by, t1.other_info

暫無
暫無

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

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