Oracle SQL查询,用于查找count = 1或count>1时不存在的工资支票

qij5mzcb  于 2022-11-03  发布在  Oracle
关注(0)|答案(1)|浏览(154)

我有一个名为Paychecks的表。在该表中,我有Employee_ID、Employee_Record和Paycheck_nbr。我的表中有错误数据,即每个Employee_ID的Paycheck_nbr都应该是唯一的。我需要过滤掉这些错误数据,并只为Employee_ID获取一个唯一的Paycheck_nbr。
错误数据示例
| 员工标识|职员_记录|工资支票_编号|
| - -|- -|- -|
| 一百二十三|三个|九十九|
| 四百五十六人|2个|九十九|
| 七百八十九|2个|九十九|
良好数据示例
| 员工标识|职员_记录|工资支票_编号|
| - -|- -|- -|
| 一百二十三|一个|九十七|
| 四百五十六人|2个|九十八|
| 七百八十九|三个|九十九|

njthzxwz

njthzxwz1#

不完全确定,但在我看来,它像是试图重新组织员工数据(不好/混乱/不独特)。如果它是试图使数据更独特,并以某种顺序,你可以尝试处理它如下:

--  First the sample data (this is not the part of answer - just some data to work with)
WITH
    a_table AS
        (
            Select '123' "EMPLOYEE_ID", 3 "EMPLOYEE_RECORD", 99 "PAYCHECK_NBR" From DUAL Union All
            Select '456' "EMPLOYEE_ID", 2 "EMPLOYEE_RECORD", 99 "PAYCHECK_NBR" From DUAL Union All
            Select '789' "EMPLOYEE_ID", 2 "EMPLOYEE_RECORD", 99 "PAYCHECK_NBR" From DUAL 
        )
--  --------   the answer   -----------------
Select
    EMPLOYEE_ID "EMPLOYEE_ID",
    --
    -- reindexing EMPLOYEE_RECORD - generate indexes ordered by EMPLOYEE_ID
    Count(1) OVER(ORDER BY EMPLOYEE_ID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) "EMPLOYEE_RECORD",
    --
    -- calculate PAYCHECK NUMBER - preserve max PAYCHECK_NMBR and calculate the rest of them ordered by new indexes
    Max(PAYCHECK_NBR) OVER() -      Count(EMPLOYEE_ID) OVER() +     Count(1) OVER(ORDER BY EMPLOYEE_ID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) "PAYCHECK_NBR"
    -- max is 99 ------             ---- number of employees = 3    --- new indexes are [1, 2, 3]  ---------
From
    a_table
Order By 
    EMPLOYEE_ID

结果如下:
| 员工标识|员工_记录|工资支票编号|
| - -|- -|- -|
| 一百二十三|一个|九十七|
| 四百五十六人|2个|九十八|
| 七百八十九|三个|九十九|
我使用了解析函数来完成这项工作。更多关于它们的信息请点击这里:https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions004.htm#SQLRF06174
......如果我们再添加一些示例行,并对EMPLOYEE_RECORD和PAYCHECK_NBR列进行更改,混合数据如下所示:

WITH
    a_table AS
        (
            Select '123' "EMPLOYEE_ID", 3 "EMPLOYEE_RECORD", 90 "PAYCHECK_NBR" From DUAL Union All
            Select '456' "EMPLOYEE_ID", 2 "EMPLOYEE_RECORD", 97 "PAYCHECK_NBR" From DUAL Union All
            Select '789' "EMPLOYEE_ID", 3 "EMPLOYEE_RECORD", 97 "PAYCHECK_NBR" From DUAL Union All
            Select '890' "EMPLOYEE_ID", 4 "EMPLOYEE_RECORD", 99 "PAYCHECK_NBR" From DUAL Union All
            Select '903' "EMPLOYEE_ID", 4 "EMPLOYEE_RECORD", 96 "PAYCHECK_NBR" From DUAL Union All
            Select '956' "EMPLOYEE_ID", 6 "EMPLOYEE_RECORD", 99 "PAYCHECK_NBR" From DUAL 
        )

...结果数据集仍将以相同的方式重新组织...
| 员工标识|员工_记录|工资支票编号|
| - -|- -|- -|
| 一百二十三|一个|九十四人|
| 四百五十六人|2个|九十五个|
| 七百八十九|三个|九十六个|
| 八百九十|四个|九十七|
| 九零三|五个|九十八|
| 九五六|六个|九十九|
此致。

相关问题