SQL:告诉列是否相互独立

时间:2009-01-02 18:30:09

标签: sql

假设我有一张桌子:

Role
----
person_id company_id financial_year

我该如何判断以下内容:

  1. 此表中每个financial_id每个person_id最多是否出现一次
  2. 如果1.为false,哪个person_id与company_id和financial_year共同出现
  3. 编辑1:编辑添加financial_year col

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

4 个答案:

答案 0 :(得分:4)

首先,如果你想要一个分组,你可以随后过滤它通常是一个好主意:

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

答案 1 :(得分:0)

这应该做你需要的:

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),但我所知道的唯一可能改变的是表别名语法,其余的是ANSI SQL。这将为每个重复的人/公司/年组合返回一行,并计算重复组合的次数(虽然问题中未提及计数,但我知道它有时可能有用)。

答案 2 :(得分:0)

我认为这样做会为#1:

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

(编辑:如果两个count()不同,那么该表包含三列的每个唯一组合的多行,我在问题#1中提出的问题。根据它们的不同来得到数量这样的行。)

和casperOne的答案将为#2

答案 3 :(得分:0)

是的,一般来说,要检测重复项,

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),关于每个person_id是否每个company_id最多出现一次,每个financial_id在此表中

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

和(2):(当(1)为假时,哪个person_id与company_id和financial_year共同出现不止一次

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