我有一张桌子:
ID Status Date
1 Stop 01.01.2001
1 Run 02.01.2002
2 Stop 03.01.2003
2 Run 04.01.2004
我想按如下方式对行进行分组:
ID Stop Run
1 01.01.2001 02.01.2002
2 03.01.2003 04.01.2004
制作这个小组的最佳方法是什么?
答案 0 :(得分:1)
select id,
max(case when status = 'Stop' then date end) as stop,
max(case when status = 'Run' then date end) as run
from your_table
group by id
答案 1 :(得分:0)
使用以下查询来使用
获取输出select ID,
MIN(case when action = 'Stop' then dateval end) STOP,
MIN(case when action = 'Run' then dateval end) RUN
from my_table
group by id;
要使用GROUP BY,您需要使用一些聚合函数。因此,您可以使用MIN或MAX
查询测试数据:
with my_table as
(
select 1 id, 'Stop' action, '01.01.2001' dateval from dual
union
select 1 id, 'Run' action, '02.01.2002' dateval from dual
union
select 2 id, 'Stop' action, '03.01.2003' dateval from dual
union
select 2 id, 'Run' action, '04.01.2004' dateval from dual
)
select ID,
MIN(case when action = 'Stop' then dateval end) STOP,
MIN(case when action = 'Run' then dateval end) RUN
from my_table
group by id
答案 2 :(得分:0)
使用
,可以使用以下查询完成相同的操作:
SELECT *
FROM (SELECT ID,dateval,action
FROM my_table)
PIVOT (max(dateval) FOR (action) IN ('Stop' AS STOP, 'Run' AS RUN));
查询测试数据:
with my_table as
(
select 1 id, 'Stop' action, '01.01.2001' dateval from dual
union
select 1 id, 'Run' action, '02.01.2002' dateval from dual
union
select 2 id, 'Stop' action, '03.01.2003' dateval from dual
union
select 2 id, 'Run' action, '04.01.2004' dateval from dual
)
SELECT *
FROM (SELECT ID,dateval,action
FROM my_table)
PIVOT (max(dateval) FOR (action) IN ('Stop' AS STOP, 'Run' AS RUN));