2012-02-17 64 views
0

我很努力地使用我最初認爲應該很簡單的SQL查詢。SQL - 選擇具有所有其他行的平均值的唯一行

想象一個表Users一個使用UserID作爲PK和用戶的年齡一欄Age

UserID  Age 
    1   22 
    2   34 
    3   23 
    4   19 
    etc. 

我希望能夠指定一個用戶名,並返回該用戶的年齡以及所有其他用戶的平均年齡。例如,如果我指定用戶ID 1然後我希望看到回報設定爲:

UserID  Age  AvgAge 
    1   22  24.5 

下不工作:(爲WHEREGROUP BY之前執行)

Select UserID, Age, Avg(Age) as 'AvgAge' 
    From Users 
    Where UserID = 1 
    Group By UserId, Age 

    UserID  Age  AvgAge //Result set 
    1   22  22 

任何人可以在正確的方向推動我?

順便說一句,在一個理想的世界的平均年齡應該包括已被指定爲思想是,以顯示他們的年齡相對於其他人的平均年齡用戶。

鑑於有超過1000個用戶,然後取平均值超過所有用戶都將令到AvgAge數量沒有實際的區別,但如果有人想炫耀了一個解決方案,以他們的實力SQL然後我有興趣看見了。

感謝

回答

3
declare @T table 
(
    UserID int, 
    Age int 
) 

insert into @T values 
    (1,   22), 
    (2,   34), 
    (3,   23), 
    (4,   19) 

declare @UserID int = 1 

select Age, (select avg(Age*1.0) 
      from @T 
      where UserID <> @UserID) as AvgAge 
from @T 
where UserID = @UserID 

結果:

Age   AvgAge 
----------- --------------------------------------- 
22   25.333333 
+0

我假設'* 1.0'確保'AVG'產生一個float而不是一個整數? – 2012-02-17 11:55:37

+0

@Remnant - 是的。否則,假設'Age'和'int'是'25'。 – 2012-02-17 11:59:06

+0

@Remnant - 在這種情況下,它實際上不是'float',而是'numeric(38,6)'。 – 2012-02-17 12:01:49

1

使用你所需要的avg的平均max最大年齡:

Select 
UserID, 
Age, 
(select Max(Age) from Users) as 'AvgAge' 
    From Users 
    Where UserID = 1 
1
SELECT 
    u.UserId, 
    u.Age, 
    b.AvgAge 
FROM 
    dbo.Users a, 
    (SELECT AVG(Age*1e0) as AvgAge FROM dbo.Users) as b 
+0

有沒有'WHERE'子句指定用戶? – 2012-02-17 11:53:15

+0

結果將是具有平均年齡的用戶表(實際上每個查詢總是相同的數字),所以如果您想添加WHERE子句,則這是基本的SQL知識 WHERE u.UserId = alexsuslin 2012-02-17 11:58:37

+0

非常感謝。 +1。我對'WHERE'的評論是用輕鬆的方式寫的! – 2012-02-17 12:01:19

1
Select U.UserID, u.Age, sq.Age as 'AvgAge' 
     From Users u 
     join (select average(age) as Age from users) sq on 1=1 
     Where UserID = 1 
     Group By UserId, Age 
+0

'1 = 1'做什麼? – 2012-02-17 12:57:39

+0

只需一個條件來強制連接匹配每條記錄(在這種情況下,只有一條記錄) – Sparky 2012-02-17 14:19:08

2

該查詢排除與平均值的指定ID的用戶,按要求。你在你的例子中使用了MAX,這不會給你平均值,但如果MAX實際上是你想要的,你可以在這個查詢中將它與AVG交換,並且它會工作。

SELECT u.UserID, 
     u.Age, 
     (SELECT AVG(uavg.Age) 
      FROM Users uavg 
      WHERE uavg.UserID != u.UserID) AS AvgAge 
    FROM Users u 
    WHERE u.UserID = 1 
+0

謝謝。 '+ 1'。我會和Mikael一起回答,因爲他的查詢返回一個浮點數,而你的查詢返回的是一個整數'26',但同樣很好。謝謝。 – 2012-02-17 11:57:54

+0

很酷。 MySQL返回一個浮點數,所以這是我今天瞭解到的一個很好的SQL-Server技巧:) – 2012-02-17 12:01:12

1
declare @T table (UserID int, Age int) 
insert into @T values(1,22),(2,34),(3,23),(4,19) 

declare @UserID int = 1 

;with a as 
(
    select userid, Age, 
    avg(age * case when userid <> @userid then 1.0 end) over() 'AvgAge' 
from @T    
) 
select Age, AvgAge from a 
where userid = @UserID 
相關問題