代码之家  ›  专栏  ›  技术社区  ›  ʞɔıu

SQL:告诉列之间是否唯一

sql
  •  0
  • ʞɔıu  · 技术社区  · 16 年前

    假设我有一张桌子:

    Role
    ----
    person_id company_id financial_year
    

    我怎样才能知道以下情况:

    1. 此表中每个人在每个公司的每个财政年度是否最多出现一次
    2. 如果是1。是假的,哪个人和公司的身份证和财政年度的共同发生不止一次

    编辑1:编辑以添加财务年度列

    编辑2:这里的RDBMS平台恰好是MySQL,不过我不认为这需要很多特定于供应商的SQL

    4 回复  |  直到 16 年前
        1
  •  4
  •   Jonathan Leffler    16 年前

    首先,最好只进行分组,然后根据需要进行筛选:

    select
      r.company_id, r.person_id, r.financial_year, count(r.person_id) 
    from
      Role as r 
    group by
      r.company_id, r.person_id, r.financial_year
    

    对于第二个问题,您可以这样修改上面的内容:

    select
      r.company_id, r.person_id, r.financial_year, count(r.person_id) 
    from
      Role as r 
    group by
      r.company_id, r.person_id, r.financial_year
    having
      count(r.person_id) > 1
    
        2
  •  0
  •   Harper Shelby damiankolasa    16 年前

    这应该可以满足您的需要:

    select left.person_id, left.company_id, left.financial_year, count(*)
    from role left
    inner join role right
        on left.person_id = right.person_id 
            and left.company_id = right.company_id
            and left.financial_year = right.financial_year
    group by left.person_id, left.company_id, left.financial_year
    

    请注意,这是T-SQL(MS),但我知道的唯一可能更改的是表别名语法,因为其余的是ANSISQL。这将为每个重复的个人/公司/年份组合返回一行,并对重复组合的次数进行计数(尽管问题中没有提到该计数,但我知道它有时很有用)。

        3
  •  0
  •   ʞɔıu    16 年前

    我认为这对1:

    select count(*), count(distinct person_id, company_id, financial_year)
        from role
    

    (编辑:如果两个count()不同,那么表中每三列的唯一组合包含多行,这是我在问题1中问的。利用它们之间的差异来获得这样的行数。)

    卡斯佩龙的回答将有助于2

        4
  •  0
  •   Charles Bretana    16 年前

    是的,一般来说,为了检测重复,

    Select [ColumnList you want to be unique]
    From Table
    Group By [SameColumn List]
    Having Count(*) > 1
    

    在你的具体情况下

    Select person_id, company_id, financial_year
    From Table
    Group By person_id, company_id, financial_year
    Having Count(*) > 1
    

    或者,对于您的子问题(1),关于每个人在本表中每个公司每个财政年度是否最多出现一次

    Select company_id, financial_year
    From Table
    Group By company_id, financial_year
    Having Count(Person_Id) > 1
    

    对于(2):(当(1)为假时,哪个人和公司以及财政年度的合并发生了不止一次

    Select person_id, company_id, financial_year
    From Table T
    Where Not Exists 
         (Select * From Table
          Where company_id = T.company_id 
             And financial_year = T.financial_year          
          Having Count(Person_Id) > 1)
    Group By person_id, company_id, financial_year
    Having Count(*) > 1