Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 28th, 2012  |  syntax: None  |  size: 1.66 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. SQL - Select unique row with average of all other rows
  2. UserID     Age
  3.     1          22
  4.     2          34
  5.     3          23
  6.     4          19
  7.     etc.
  8.        
  9. UserID      Age      AvgAge
  10.    1           22       24.5
  11.        
  12. Select UserID, Age, Avg(Age) as 'AvgAge'
  13.   From Users
  14.   Where UserID = 1
  15.   Group By UserId, Age
  16.  
  17.   UserID      Age      AvgAge    //Result set
  18.   1           22       22
  19.        
  20. declare @T table
  21. (
  22.   UserID int,
  23.   Age int
  24. )
  25.  
  26. insert into @T values
  27.     (1,          22),
  28.     (2,          34),
  29.     (3,          23),
  30.     (4,          19)
  31.  
  32. declare @UserID int = 1
  33.  
  34. select Age, (select avg(Age*1.0)
  35.              from @T
  36.              where UserID <> @UserID) as AvgAge
  37. from @T
  38. where UserID = @UserID
  39.        
  40. Age         AvgAge
  41. ----------- ---------------------------------------
  42. 22          25.333333
  43.        
  44. SELECT u.UserID,
  45.         u.Age,
  46.         (SELECT AVG(uavg.Age)
  47.            FROM Users uavg
  48.           WHERE uavg.UserID != u.UserID) AS AvgAge
  49.     FROM Users u
  50.    WHERE u.UserID = 1
  51.        
  52. Select
  53.  UserID,
  54.  Age,
  55.  (select Max(Age) from Users) as 'AvgAge'
  56.   From Users
  57.   Where UserID = 1
  58.        
  59. Select U.UserID, u.Age, sq.Age as 'AvgAge'
  60.       From Users u
  61.       join (select average(age) as Age from users) sq on 1=1
  62.       Where UserID = 1
  63.       Group By UserId, Age
  64.        
  65. SELECT
  66.     u.UserId,
  67.     u.Age,
  68.     b.AvgAge
  69. FROM
  70.     dbo.Users a,
  71.     (SELECT AVG(Age*1e0) as AvgAge FROM dbo.Users) as b
  72.        
  73. declare @T table (UserID int, Age int)  
  74. insert into @T values(1,22),(2,34),(3,23),(4,19)  
  75.  
  76. declare @UserID int = 1
  77.  
  78. ;with a as
  79. (
  80.   select userid, Age,
  81.   avg(age * case when userid <> @userid then 1.0 end) over() 'AvgAge'
  82. from @T            
  83. )
  84. select Age, AvgAge from a
  85. where userid = @UserID