[英]grouping multiple fields using sql
After doing some joins and stuff I have table in the following format 经过一些连接和东西后,我有以下格式的表
name session_id status time
abc 1 10
xyz 2 11
jack 2 10
zuck 1 10
paul 1 10
Now I want my results to be grouped like this 现在,我希望将结果像这样分组
session_id name+status time
1 abc:10, zuck:10, paul:10
2 xyz:11, jack:11
and the result set to be sorted by time, I'm little confused how to achieve this using group by 并将结果集按时间排序,我有点困惑如何使用group by实现
if your db is oracle, you can try. 如果您的数据库是oracle,则可以尝试。 Afer oracle 11g r2, you can also use listagg
在oracle 11g r2之后,您也可以使用listagg
select session_id, wm_concat(name_status), time from
(
select session_id, (name+':'+status) as name_status, time
from stuff
)
group by session_id
order by time
SELECT
session_id
, GROUP_CONCAT( CONCAT(name, ':', COALESCE(status, -1)
SEPARATOR ', '
ORDER BY `time`
) AS name_status
, MIN(`time`) AS min_time --- or MAX(`time`)
FROM
TableX
GROUP BY
session_id
ORDER BY
min_time
You could use time
instead of MIN(time)
, if all rows with same session_id
have same time
(if time
is functionally dependent on session_id
). 如果所有具有相同
session_id
行都具有相同的time
(如果time
在功能上取决于session_id
),则可以使用time
而不是MIN(time)
)。 If that's not the case and you use time
, you'll not get consistent results on that column. 如果不是这种情况,并且您使用
time
,那么在该列上将无法获得一致的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.