有一个SUM()函数sql的上限

时间:2011-12-07 14:56:20

标签: sql sql-server

我在SQL查询的select语句中进行了一个小的计算:

SELECT 
   (select sum(weighting) 
     from table1 
     where id = tablemain.id) * 
   (select sum(weighting) 
     from table2 
     where id = tablemain.id) as rating
from 
  tablemain

我遇到的问题是这些SUM值之一的上限应为8, 例如如果权重列的SUM达到10,那么它应该只乘以8。

有人对select声明中如何做到这一点有什么想法,或者它是否可行?

由于

4 个答案:

答案 0 :(得分:4)

您可以尝试一个案例陈述。我甚至会选择CTE中的值来简化代码,但原理是一样的。

SELECT  
   (select CASE WHEN sum(weighting) > 8 THEN 8 ELSE sum(weighting) END 
     from table1  
     where id = tablemain.id) *  
   (select CASE WHEN sum(weighting) > 8 THEN 8 ELSE sum(weighting) END 
     from table2  
     where id = tablemain.id) as rating 
from  
  tablemain 

答案 1 :(得分:1)

注意:感谢Leons指出这一点,以下内容不起作用,因为 min 仅根据http://msdn.microsoft.com/en-us/library/ms179916.aspx获取一个参数:

select min(8, sum(weighting)) ...

答案 2 :(得分:1)

小心查询。现在它将为tablemain中的每一行执行2个相关子查询。另一种方法是使用连接和分组。在你的情况下测试更快。

SELECT id, 
 (CASE WHEN t1.w > 8 THEN 8 ELSE t1.w END) *
 (CASE WHEN t2.w > 8 THEN 8 ELSE t2.w END) rating
FROM tablemain as t, (select id, sum(weighting) w  from table1 group by id) as t1, (select id, sum(weighting) w from table2 group by id) as t2
WHERE t.id = t1.id and t.id = t2.id

答案 3 :(得分:1)

避免相关子查询而不会造成大量重复的替代方法......

SELECT id, 
 (CASE WHEN (t1.weight > 8) THEN 8 ELSE t1.weight END) *
 (CASE WHEN (t2.weight > 8) THEN 8 ELSE t2.weight END)             AS rating
FROM
  tablemain                                                        AS t
LEFT JOIN
  (SELECT id, SUM(weighting) AS weight FROM table1 GROUP BY id)    AS t1
    ON t1.id = t.id
LEFT JOIN
  (SELECT id, SUM(weighting) AS weight FROM table2 GROUP BY id)    AS t2
    ON t2.id = t.id