查询

时间:2017-04-06 20:06:13

标签: sql sql-server

这是我的疑问:

Select id, t1.column1 * t1.column2 as SUM from t1 Inner Join t2 on t1.id = t2.id

执行后获取此结果https://postimg.org/image/r6yu7rp7n/

如何在查询中添加GROUP BY ID?

3 个答案:

答案 0 :(得分:3)

如果你只是需要来自t1的字段应该只做

Select t1.id, 
       sum(t1.column1 * t1.column2) as SUM 
from t1 
Inner join t2 on t1.id = t2.id 
group by t1.id

如果需要应用一些过滤器

Select t1.id, 
       sum(t1.column1 * t1.column2) as SUM 
from t1 
Inner join t2 on t1.id = t2.id 
where t2.someField = someValue
group by t1.id

但是,如果你需要显示每一行的值和组的总数,你可以使用像这样的窗口函数

Select t1.*, 
       t2.*, 
       sum(t1.column1 * t1.column2) over (partition by t1.id) as SUM 
from t1 Inner Join t2 on t1.id = t2.id

答案 1 :(得分:1)

你的意图不明确。可能这就是你的意思(总结t1.column1 * t1.column2按ID分组,t1.id存在于t2中):

Select t1.id, sum(t1.column1 * t1.column2) as SUM 
from t1 where exists 
(select * from t2 where t1.id = t2.id)
group by t1.id;

注意:不要对连接的表进行求和。总和和加入(这里我认为加入没有目的)。

答案 2 :(得分:0)

像这样

Select t1.id, SUM(t1.column1 * t1.column2) as SUM 
from t1 Inner Join t2 on t1.id = t2.id 
group by t1.id