0

我有一张桌子(简化如下)

|company|name |age|
| 1     |  a  | 3 | 
| 1     |  a  | 3 | 
| 1     |  a  | 2 | 
| 2     |  b  | 8 | 
| 3     |  c  | 1 | 
| 3     |  c  | 1 | 

由于各种原因,每个公司的年龄列应该相同。我有另一个更新此表的过程,有时它输入了不正确的年龄。对于公司 1,年龄应始终为 3

我想找出哪些公司的年龄不匹配。

我已经这样做了

select company, name age from table group by company, name, age

但不知道如何获取年龄不同的行。这张桌子要宽得多,而且有很多列,所以我真的看不出来。

任何人都可以帮忙吗?

谢谢

4

3 回答 3

3

您不应该包含age在 group by 子句中。

SELECT  company
FROM    tableName
GROUP   BY company, name
HAVING  COUNT(DISTINCT age) <> 1
于 2013-09-29T21:01:17.373 回答
0

既然您提到了“如何获取年龄不同的行”而不仅仅是公司:

如果还没有,请添加唯一的行 ID(主键)。让我们称之为id

然后做

select id from table 
where company in 
    (select company from table 
    group by company 
    having count(distinct age)>1)
于 2013-09-29T21:05:37.227 回答
0

如果要查找年龄与每个公司/名称组的最大计数年龄不同的行:

WITH CTE AS
(
    select company, name, age,
           maxAge=(select top 1 age
             from dbo.table1 t2
             group by company,name, age
             having( t1.company=t2.company and t1.name=t2.name)
             order by count(*) desc)
    from dbo.table1 t1 
)
select * from cte 
where age <> maxAge

Demontration

如果你想用正确的年龄更新不正确的,你只需SELECT要用UPDATE

WITH CTE AS
(
    select company, name, age,
           maxAge=(select top 1 age
             from dbo.table1 t2
             group by company,name, age
             having( t1.company=t2.company and t1.name=t2.name)
             order by count(*) desc)
    from dbo.table1 t1 
)
UPDATE cte SET AGE = maxAge 
WHERE age <> maxAge

Demonstration

于 2013-09-29T21:24:19.100 回答