如何从SQL Server数据库中检索输入最多的值?

时间:2011-01-10 12:49:16

标签: .net sql vb.net ado.net

如果我有mssql数据库,下面显示了记录:

Id           Serv-code          Value
1            100                3
2            100                4
3            100                3
4            100                3
5            101                5
6            101                5

当我使用serv_code 100搜索记录时我想要的逻辑然后输出将是平均值3将显示在文本框中,因为值3将输入3次,如上所示....并且如果如果我用serv_code 100搜索记录,如果serv_code的值相等则表示只有3和4,那么最近输入的值将显示在文本框中..

2 个答案:

答案 0 :(得分:2)

你的问题令人困惑。但要回答具有平均值的部分: 你应该在数据库方面使用AVG-SQL-Function这样做:

CREATE TABLE #Temp (
Id              int,
ServCode        INT,
Value           INT)

INSERT INTO #Temp Values(1,100,3)
INSERT INTO #Temp Values(2,100,4)
INSERT INTO #Temp Values(3,100,3)
INSERT INTO #Temp Values(4,100,3)
INSERT INTO #Temp Values(5,101,5)
INSERT INTO #Temp Values(6,101,5)

select AVG(Value)FROM #Temp WHERE ServCode=100

drop table #Temp

使用此选项在查询中创建一个额外的列,其中包含每行的Serv-Code的平均值:

 SELECT  T1.*,
    (SELECT AVG(Value)
        FROM [#Temp] AS T2
    WHERE T1.ServCode=T2.ServCode) AS average
 FROM [#Temp] AS T1

答案 1 :(得分:0)

with occurrences as (select value, occurrences, rank() over(order by occurrences desc) as rank
                     from (select value, count(*) as occurrences
                           from @data where serv_code = 101 group by value
                          ) count_occurrences
                     )
select case when (select count(*) from occurrences where rank = 1) > 1
            then (select top 1 data.value from @data data join occurrences on data.value = occurrences.value where data.serv_code = 101 and occurrences.rank = 1 order by id desc)
       else (select value from occurrences where rank = 1)
       end as value;