【问题标题】:Select all rows if there are id duplicates then select the one (of 2) with particular type如果有 id 重复,则选择所有行,然后选择具有特定类型的(2 个)
【发布时间】:2017-03-18 01:19:41
【问题描述】:

我有一张桌子

其中一些“job_id”(“job_id”列)有重复项。我需要从该表中选择所有列。如果“job_id”列中有重复项,则选择类型为“Pending Starts”的行(从“type”列中)。我也尝试将表连接到自身,但它也不起作用。

select  *
case x.job_id
    when count(*)>1 then x.type="Pending Starts"
    end as type
from X

【问题讨论】:

    标签: mysql sql distinct amazon-redshift


    【解决方案1】:

    使用两个查询的联合。查找所有没有重复作业 ID 的行。另一个查找所有重复的作业 ID 并返回带有 type = 'PendingStarts' 的行。

    SELECT a.*
    FROM X AS a
    JOIN (SELECT job_id
          FROM X
          GROUP BY job_id
          HAVING COUNT(*) = 1) AS b
    ON a.job_id = b.job_id
    
    UNION ALL
    
    SELECT a.*
    FROM X AS a
    JOIN X AS b ON a.job_id = b.job_id
    WHERE a.type = 'PendingStarts'
    AND b.type != 'Pending Starts'
    

    我假设当有重复时,类型是不同的。

    【讨论】:

    • 谢谢!错误:42803:列“X.data_date”必须出现在 GROUP BY 子句中或用于聚合函数
    • 您可以关闭ONLY_FULL_GROUP_BY SQL模式,或者在我的回答中使用更新后的查询。
    • 谢谢你,在第二部分我假设你加入“ON a.job_id=y.job_id”而不是 b.job_id。但无论如何我有这个错误 ERROR: 42601: each UNION query must have the same number of columns
    • 我的意思是JOIN X AS b。两个查询应该有相同数量的列,因为a.* 在两者中是相同的。也许你写的是SELECT *而不是SELECT a.*
    【解决方案2】:

    你总是想要 Pending Starts 值,所以从那个开始:

    select t.*
    from t
    where t.type = 'Pending Starts'
    union all
    select t.*
    from t
    where not exists (select 1
                      from t t2
                      where t2.job_id = t.job_id and t2.type = 'Pending Starts'
                     );
    

    这不是您的问题所要求的,但它似乎是您可能想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      • 2021-12-11
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      相关资源
      最近更新 更多