【问题标题】:Selecting records with duplicate number in one column, and a unique string in another选择一列中重复编号的记录,另一列中选择唯一字符串
【发布时间】:2017-01-05 02:16:53
【问题描述】:

我有一个 Postgres 记录表,其中包括许多具有 reg_number 的新归档帐户,以及许多现在已使用相同 reg_number 完成的归档帐户。

由于不一致,我无法按日期或行号查询。

我需要能够选择:
任何归档的行 - 尚未最终确定,
任何已完成的行,但不是其原始“归档”行。

源数据表

reg_num   |  file_final   |  otherCols  
1234      |   filed       |   foo  
1234      |   final       |   foo  
1235      |   filed       |   foo  
1218      |   filed       |   foo  
1111      |   final       |   foo  
1235      |   final       |   foo  

想要的选择:

reg_num   |  file_final  |  otherCols  
1234      |   final      |   foo  
1218      |   filed      |   foo  
1111      |   final      |   foo  
1235      |   final      |   foo  

我尝试了多种 SELECT DISTINCT ON 和 JOINS 的组合,但是我卡住了。
上面显示了两个相关字段,整个表还有大约 25 个其他列,
我需要能够从中进行选择。

任何帮助将不胜感激。谢谢!
我尝试过的一些查询(10 多个)包括:

选择 *
FROM ca_enforce
在哪里注册号码
(
SELECT DISTINCT ON (reg_number) reg_number
WHERE file_final = 'Final' 或 file_final = '归档'
按 reg_number 分组
);

另一个:

在 reg_number 上选择 DISTINCT,
身份证,
col3,
col4,
文件_最终,
col6,
col7,
注册号
WHERE file_final = '决赛'
FROM my_table
按 file_final 排序;

【问题讨论】:

    标签: sql database postgresql


    【解决方案1】:

    联合技术强制 PostGreSQL 对数据进行两次传递。

    使用 reg_num 列上的索引,以下查询应该执行得更快:

    select reg_num, file_final, otherCols
    from t t1
    where file_final = 'final' or not exists (
      select *
      from t t2
      where t2.reg_num = t1.reg_num and t2.file_final = 'final');
    

    【讨论】:

    • 感谢两位回复。我接受了这个,因为它以最少的调整给出了结果......这只是因为我必须将两个“t”表引用更改为相同的 schema.table 名称。谢谢!这有助于揭示数据源方法中的一个巨大缺陷,即错误分类了大约 30% 的记录。
    【解决方案2】:

    听起来像是两个可以联合在一起的查询:

    --get all of the filed records that don't have final records.
    select reg_num
    from my_table
    where reg_num not in (
      select reg_num
      from my_table
      where final_file = 'final'
    )
    where final_file = 'file'
    
    union all
    --get all of the final records.
    select reg_num
    from my_table
    where file_final = 'final'
    

    【讨论】:

      【解决方案3】:
      select reg_num,file_final,othercols
      from table_name
      where reg_num not in (
                    select reg_num
                    from table_name
                     where final_file = 'final'
                           )
      union all
      select reg_num,file_final,othercols
      from table_name
      where file_final = 'final'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 2023-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多