Sql server在查询中暂存操作

时间:2018-05-24 21:31:58

标签: sql sql-server

我有一张这样的表

id | userId | point | type
1     3        3       1
2     3        5       1 
3     3        6       1
4     3        2       2
5     4        5       1

我想得到的是

userId | totalPoint
  3         28
  4         5

我计算的方法是对所有类型为1的点进行求和,并将该和的总和乘以类型为2的点

示例:(3 + 5 + 6)* 2 = 28

我尝试了很多查询,但我无法得到它

感谢任何帮助

3 个答案:

答案 0 :(得分:1)

这比它最初看起来有点棘手。您需要条件聚合,并且要注意缺少“2”值:

select userid,
       (sum(case when type = 1 then point else 0 end) *
        coalesce(sum(case when type = 2 then point end), 1)
       )
from t
group by userid;

答案 1 :(得分:0)

使用此数学技巧创建产品聚合:

 SELECT
       userid, 
       exp(SUM(LOG(ABS(NULLIF(field, 0)))))  
    FROM
       (select distinct userid, type, sum(point) over(partition by userid, type order by userid)field  from #temp 
group by userid, type, point)a
    GROUP BY
       userid

答案 2 :(得分:0)

尝试仅使用SELECT,子查询和分组

SELECT USER_ID,
     (SELECT SUM(POINT) FROM THETABLE b 
        WHERE a.USER_ID = b.USER_ID AND TYPE = 1
        GROUP BY b.USER_ID, TYPE)
             *
     (SELECT SUM(POINT) FROM THETABLE c
        WHERE a.USER_ID = c.USER_ID AND TYPE = 2
        GROUP BY b.USER_ID, TYPE)
     AS TOTAL_POINT
 FROM THETABLE a