2011-01-10 283 views
0

如果我有MSSQL數據庫記錄下面顯示:如何從SQL Server數據庫中檢索最大輸入值?

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

你的問題很混亂。但是,爲了回答與平均值的部分: 你應該用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-代碼創建查詢一個額外的列:

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

爲什麼AVG在這裏使用/先生...... – 2011-01-10 15:52:59

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; 
相關問題