分组和总值

时间:2011-10-04 19:57:33

标签: sql sql-server sql-server-2005

 Id       User Val1 Val2
 11910115 Fred 123 -0.000137
 11910116 Fred 456 0
 11910117 Fred 789 0.0002
 11910118 Sue 101 8.7E-05
 11910119 Sue 102 0.000125
 11910120 Sue 103 0

意图:

Select Id,User,Val1,Max(abs(val2)) val2
From MyTable
Group By User

我所追求的是:

11910117 Fred 789 0.0002
11910119 Sue 102 0.000125

我满意的是:

11910117 0.0002
11910119 0.000125

但是,我无法绕过'在选择列表中无效,因为它不包含在聚合中......'

5 个答案:

答案 0 :(得分:1)

非聚合的每个字段都应显示在组中。所以假设你想要汇总val1:

Select Id, User, max(Val1) val1, max(abs(val2)) val2
From MyTable
Group By Id, User

答案 1 :(得分:1)

SELECT y.Id, y.User, y.Val1, t.MaxVal
    FROM YourTable y
        INNER JOIN (SELECT User, MAX(ABS(val2)) AS MaxVal
                        FROM YourTable
                        GROUP BY User) t
            ON y.User = t.User
                AND ABS(y.Val2) = t.MaxVal
    WHERE y.User = 'Fred'

答案 2 :(得分:0)

select Id, User, Val1, Val2
from MyTable t1
where not exists
(
   select * 
   from MyTable t2
   where t2.Id != t1.Id
   and   t2.User = t1.User
   and   abs(t2.Val2) > abs(t1.Val2) 
)

答案 3 :(得分:0)

试一试

SELECT t.id, t.user, t.val1, t.val2
FROM mytable t
    INNER JOIN
        (SELECT user, MAX(ABS(val2)) AS max
        FROM mytable
        GROUP BY user) q ON t.user = q.user AND ABS(t.val2)=q.max

不确定这会对您的桌子有多高效。

答案 4 :(得分:0)

select Id,
       [User],
       Val1,
       Val2
from (
      select Id,
             [User],
             Val1,
             Val2,
             row_number() over(partition by [User] order by abs(Val2) desc) as rn
      from YourTable
      -- where ... goes here
     ) as T
where rn = 1

http://data.stackexchange.com/stackoverflow/q/114300/