您好我正在寻找一种编写SQL语句的方法,该语句将产生以下结果: -
让我们说我们有Dept& Emp ID我想从第3部分为前两行生成类似的记录,然后是部门2,然后是一行,然后继续部门3,依此类推:
DEPT EMPID
----- ------
3 1
3 2
2 3
3 7
3 8
2 9
谢谢。
答案 0 :(得分:1)
你可以使用这样的东西
SELECT
DEPT,
EMPID
FROM (
SELECT
*,
ceil((row_number() OVER (PARTITION BY dept ORDER BY EMPID ))/ 2::numeric(5,2)) AS multiple_row_dept,
row_number() OVER (PARTITION BY dept ORDER BY EMPID ) AS single_row_dept
FROM
test_data2
) sub_query
ORDER BY
CASE
WHEN DEPT = 2 THEN single_row_dept
ELSE multiple_row_dept
END,
DEPT DESC,
EMPID
single_row_dept
个细节,哪些部门只应出现一次,在这种情况下,其DEPT 2
后跟多个其他部门
答案 1 :(得分:0)
首先在子查询中按empid排序表,
然后计算剩余的rowid除以3,
然后根据计算结果,使用case
表达式返回2或3,
像这样
SELECT
CASE REMAINDER( rownum, 3 )
WHEN 0 THEN 2
ELSE 3
END As DeptId,
empid
FROM (
SELECT empid
FROM table1
ORDER BY empid
)
答案 2 :(得分:0)
以下代码有一些限制:
1)源表中只有2个DepId
2)具有不同DepId的记录之间的比率恰好是2:1
3)应该更改在查询的一个位置的排序,这取决于DeptId是否有更多记录自然大于另一个
with t as (
select 3 dept_id, 1 emp_id from dual
union all
select 3, 2 from dual
union all
select 3, 7 from dual
union all
select 3, 8 from dual
union all
select 2, 3 from dual
union all
select 2, 9 from dual)
select dept_id, emp_id
from (select dept_id,
emp_id,
dense_rank() over(partition by dept_id order by in_num + mod(in_num, out_num)) ord
from (select dept_id,
emp_id,
row_number() over(partition by dept_id order by emp_id) in_num,
/*in the following ORDER BY change to DESC or ASC depending on which dept_id has more records*/
dense_rank() over(order by dept_id) out_num
from t))
order by ord, dept_id desc;
DEPT_ID EMP_ID
---------- ----------
3 1
3 2
2 3
3 8
3 7
2 9