如何选择出现2次的最大值?

时间:2016-10-12 15:11:14

标签: tsql

假设我有一个看起来像这样的值表:

   Sample_Number | 
-------------------
    1             |
    1             |
    2             |
    3             |
    3             |
    4             |
    5             |

如何编写SELECT语句以返回恰好发生2次的最大样本数?在示例数据中,我要查找的值为3。

我想可能会有很多答案 - 我对没有内部选择的解决方案特别感兴趣并使用Having子句(如果可能的话)。

5 个答案:

答案 0 :(得分:3)

我确信有一种更简单的方法可以做到这一点,但你可以通过提取所有Sample_Number只有两个条目并拉出这些值的MAX()来实现这一目标:

;With Cte As
(
    Select  Sample_Number
    From    Test
    Group By Sample_Number
    Having  Count(Sample_Number) = 2
) 
Select  Max(Sample_Number)
From    Cte

答案 1 :(得分:3)

您可以使用此查询:

SELECT TOP 1 Sample_Number As MaxSampleNumberThatOccursTwice
FROM dbo.TableName
GROUP BY Sample_Number
HAVING COUNT(*) = 2
ORDER BY Sample_Number DESC

答案 2 :(得分:1)

;with cte
as
(select sample_number
from #temp
group by Sample_Number 
having
count(Analysis_ID)=2
)
select max(sample_number) from cte

答案 3 :(得分:1)

我会使用subselect:

SELECT MAX (sample_number) 
FROM  (SELECT sample_number
        FROM TAB1
        GROUP BY sample_number
        HAVING COUNT(sample_number) =2 
        )

答案 4 :(得分:0)

按Sample_Number分组并获取组的计数 并且只选择计数是否为2

select Sample_Number, count(*) count from someTable
group by Sample_Number
having count=2