Efficiently Include Column not in Group By of SQL Query

前端 未结 3 746
故里飘歌
故里飘歌 2020-12-16 20:23

Given

Table A

Id   INTEGER
Name VARCHAR(50)

Table B

Id   INTEGER
FkId INTEGER  ;          


        
3条回答
  •  星月不相逢
    2020-12-16 21:01

    You can try something like this:

       ;WITH GroupedData AS
       (
           SELECT FkId, COUNT(FkId) As FkCount
           FROM B 
           GROUP BY FkId
       ) 
       SELECT gd.*, a.Name
       FROM GroupedData gd
       INNER JOIN dbo.A ON gd.FkId = A.FkId
    

    Create a CTE (Common Table Expression) to handle the grouping/counting on your Table B, and then join that result (one row per FkId) to Table A and grab some more columns from Table A into your final result set.

提交回复
热议问题