我有下表,其中包含有关每个小组如何解决问题的数据:
PROB | GROUP | REPNO | STATUS
-----+---------+-------+-------
1 | Juniors | 0 |
1 | Seniors | 1 |
1 | Juniors | 2 |
1 | Experts | 3 | SOLVED
2 | Juniors | 0 |
2 | Seniors | 1 | SOLVED
列PROB定义了组正在解决的问题,列GROUP定义了哪个组正在处理此问题,列REPNO定义了解决重复的次数(重复尝试直到最终解决,0表示首次尝试,还没有重复),最后一列STATUS定义了在特定尝试中是否解决了任务。在这里,我可以分配ALL GROUPS(SELECT ... GROUP BY repno)在每次重复中如何有效地解决工作。
但我想展示每个特定群体如何有效地解决probs(每个群体的分布'自己的重复顺序)。例如,PROB 1被组Juniors尝试了两次,一次被组Seniors尝试并且没有被解决,最后在小组专家的第一次尝试中解决了。
所以我需要重新计算每个特定组的重复次数:
PROB | GROUP | REPNO | REPNO_J | REPNO_S | REPNO_E | STATUS
-----+---------+-------+---------+---------+---------+-------
1 | Juniors | 0 | 0 | | |
1 | Seniors | 1 | | 0 | |
1 | Juniors | 2 | 1 | | |
1 | Experts | 3 | | | 0 | SOLVED <-- experts solved in first try
2 | Juniors | 0 | 0 | | |
2 | Seniors | 1 | | 0 | | SOLVED <-- seniors solved in first try
如何重新计算?
答案 0 :(得分:1)
使用ROW_NUMBER窗口函数获取每组的数量:
select
prob,
"GROUP",
repno,
case when "GROUP" = 'Juniors' then try end as repno_j,
case when "GROUP" = 'Seniors' then try end as repno_s,
case when "GROUP" = 'Experts' then try end as repno_e,
status
from
(
select
prob, "GROUP", repno, status,
row_number() over(partition by prob, "GROUP" order by repno) - 1 as try
from mytable
)
order by prob, repno;
顺便说一句:命名列GROUP不是一个好主意。这是SQL中的保留字。因此,只要在查询中使用名称,就必须使用引号并考虑大小写。
答案 1 :(得分:1)
USE RANK() SQL FIDDLE
select
PROB,
GROUP1,
REPNO,
DECODE(GROUP1,'Juniors', rank() over (partition by prob, group1 order by repno) - 1) as REPNO_J,
DECODE(GROUP1,'Seniors', rank() over (partition by prob, group1 order by repno) - 1) as REPNO_S,
DECODE(GROUP1,'Experts', rank() over (partition by prob, group1 order by repno) - 1) as REPNO_E,
STATUS
from mytable
order by prob,repno
答案 2 :(得分:0)
您可以使用CASE声明
SELECT "PROB",
"GROUP",
"REPNO",
(CASE WHEN "GROUP" = 'Juniors' THEN REPNO ELSE NULL END ) as REPNO_J,
(CASE WHEN "GROUP" = 'Seniors' THEN REPNO ELSE NULL END ) as REPNO_S,
(CASE WHEN "GROUP" = 'Experts' THEN REPNO ELSE NULL END ) as REPNO_E
FROM Table1