简体   繁体   English

从2个表进行分组和平均计算的SQL Server查询

[英]SQL Server query from 2 tables with grouping and average calc

I've got 2 tables in SQL Server database: 我在SQL Server数据库中有2个表:

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

What I need is query that returns table with grouped records by [opt_1] and [opt_2] like this: 我需要的是返回按[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]}

What is the best way to get it? 最好的方法是什么?

You could use join and group by ; 您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM