【问题标题】:SQL query: how to distinct count of a column group by another columnSQL查询:如何通过另一列区分列组的计数
【发布时间】:2012-11-07 02:05:37
【问题描述】:

在我的表中,我需要知道每个ID 是否有一个且只有一个ID_name。我该如何编写这样的查询?

我试过了:

select ID, count(distinct ID_name) as count_name 
from table 
group by ID 
having count_name > 1

但它需要很长时间才能运行。

有什么想法吗?

【问题讨论】:

  • 我应该补充一点,我什至不确定我的查询是否正确,因为它从未执行过!

标签: sql optimization count


【解决方案1】:
select  ID
from    YourTable
group by
        ID
having  count(distinct ID_name) > 1

select  *
from    YourTable yt1
where   exists
        (
        select  *
        from    YourTable yt2
        where   yt1.ID = yt2.ID
                and yt1.ID_Name <> yt2.ID_Name
        )

现在,大多数 ID 列被定义为 primary key 并且是唯一的。因此,在常规数据库中,您希望两个查询都返回一个空集。

【讨论】:

    【解决方案2】:

    从中选择 tt.ID,max(tt.myRank) ( 选择 ip.ID,ip.ID_name, ROW_Number() over (partition by ip.ID, ip.ID_nameorder by ip.ID) as myRank 来自 YourTable ip ) tt 按 tt.ID 分组

    这会为您提供每个 ID 及其 ID_Name 的总数

    如果您只想要那些关联多个名称的 ID,只需添加一个 where 子句 例如

    从中选择 tt.ID,max(tt.myRank) ( 选择 ip.ID,ip.ID_name, ROW_NUMBER() over (partition by ip.ID, ip.ID_nameorder by ip.ID) as myRank 来自 YourTable ip ) tt 其中 tt.myRank > 1 按 tt.ID 分组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多