簡體   English   中英

從2個表進行分組和平均計算的SQL Server查詢

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

我在SQL Server數據庫中有2個表:

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

我需要的是返回按[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]}

最好的方法是什么?

您可以使用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