用于计算具有公分母的重复实例的SQL查询

时间:2014-01-15 18:07:39

标签: sql sql-server-2008

我需要一点帮助才能使用SQL

来解决这个问题

示例数据

+------+---+---+
|height|age|sex|
+------+---+---+
|150   |21 |m  |
+------+---+---+
|160   |22 |f  |
+------+---+---+
|170   |19 |m  |
+------+---+---+
|150   |30 |m  |
+------+---+---+
|140   |44 |f  |
+------+---+---+
|150   |33 |m  |
+------+---+---+
|170   |21 |m  |
+------+---+---+

如果有多个人身高相同而其中一人是21,我需要总计数?

所以答案应该是2

2 个答案:

答案 0 :(得分:1)

select height, count(*)
from your_table
group by height
having count(*) > 1
and sum(case when age = 21 then 1 else 0 end) > 0

您可能希望这两对具有两种性别。然后添加

and count(distinct sex) = 2

答案 1 :(得分:0)

试试这个:

SELECT COUNT(*) FROM Table WHERE age = 21 AND height IN 
    (SELECT height FROM Table WHERE age <> 21);