简体   繁体   中英

Finding records sets with GROUP BY and SUM

I'd like to do a query for every GroupID (which always come in pairs) in which both entries have a value of 1 for HasData.

|GroupID | HasData |
|--------|---------|
|  1     |  1      |
|  1     |  1      |
|  2     |  0      |
|  2     |  1      |
|  3     |  0      |
|  3     |  0      |
|  4     |  1      |
|  4     |  1      |

So the result would be:

1
4

here's what I'm trying, but I can't seem to get it right. Whenever I do a GROUP BY on the GroupID then I only have access to that in the selector

SELECT GroupID
FROM Table
GROUP BY GroupID, HasData
HAVING SUM(HasData) = 2 

But I get the following error message because HasData is acutally a bit:

Operand data type bit is invalid for sum operator.

Can I do a count of two where both records are true?

just exclude those group ID's that have a record where HasData = 0.

select distinct a.groupID
from table1 a 
where not exists(select * from table1 b where b.HasData = 0 and b.groupID = a.groupID)

You can use the having clause to check that all values are 1:

select GroupId
from table
group by GroupId
having sum(cast(HasData as int)) = 2

That is, simply remove the HasData column from the group by columns and then check on it.

One more option

SELECT GroupID
FROM table
WHERE HasData <> 0
GROUP BY GroupID
HAVING COUNT(*) > 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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