来自2个表的SQL Server查询,具有分组和平均计算

时间:2018-02-03 19:19:17

标签: sql sql-server

我在SQL Server数据库中有2个表:

  • table_1:[id],[opt_1],[opt_2],[opt_3],[opt_4]
  • table_2:[id],[result]

我需要的是通过[opt_1]和[opt_2]返回带有分组记录的表的查询,如下所示:

[opt_1],
[opt_2],
{count of such records from table_1},
{count of such records from table_2, by [id]},
{average [result] from table_2, by [id]}

获得它的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用joingroup by;

select t1.opt_1,t2.opt_2,count(t1.id),AVG(t2.result) from table1 t1 
inner join table2 t2 ON t1.id = t2.id
group by t1.opt_1,t2.opt_2