简体   繁体   English

SQL组,其中组中的值相同

[英]SQL group by where values are same within group

So, I have a table with which individuals (person_id) have multiple lines (up to 4) and values for a column (value_column) can either = 0 or 1 因此,我有一张表,个人(person_id)有多行(最多4行),一列的值(value_column)可以为0或1

I'd like to write a piece of code that returns a row for each person_id in which their value for value_column is only 0 or only 1 (even though they may have 3 or 4 rows each) 我想编写一段代码,为每个person_id返回一行,其中他们的value_column值仅为0或仅为1(即使它们每个可能有3或4行)

It's probably an easy line of code, but for someone with less SQL experience, it seems nearly impossible! 这可能是简单的代码行,但是对于没有SQL经验的人来说,这似乎几乎是不可能的!

EDIT: here is a quick sample of lines: 编辑:这是行的快速示例:

person_id  value_column
A          0
A          1
A          0
B          0
B          0
B          0
B          0
C          1
C          1
C          1

And I would expect the line of code to return the folowing: 我希望代码行能够返回以下内容:

person_id value_column
B          0
C          1

You can try something like this probably 您可以尝试这样的事情

select distinct * from table1
where person_id in
( select person_id
  from table1
  group by person_id
  having count(distinct value_column) <= 1
)

Inner query, will return only those person_id for which there is only one value_column present and that's the same thing getting done by count(distinct value_column) <= 1 and then outer query just selects everything for those person_id. 内部查询将仅返回那些只存在一个value_column person_id ,并且通过count(distinct value_column) <= 1完成相同的操作,然后外部查询仅选择那些person_id的所有内容。

select * from myTable where person_id not in 
(select a.person_id from myTable a, myTable b
  where a.person_id = b.person_id
    and a.value_column <> b.value_column)

Get persons with different values and then get those who are not in this first query. 获取具有不同值的人员,然后获取不在此第一个查询中的人员。

Or quicker and nicer : 或者更快更好:

select person_id, min(value_column)
 from myTable
 group by person_id
 having min(value_column)=max(value_column)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM