Efficiently Include Column not in Group By of SQL Query

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

Given

Table A

Id   INTEGER
Name VARCHAR(50)

Table B

Id   INTEGER
FkId INTEGER  ;          


        
相关标签:
3条回答
  • 2020-12-16 20:36
    select t3.Name, t3.FkId, t3.countedFkId from (a t1 
      join (select t2.FkId, count(FkId) as countedFkId from b t2 group by t2.FkId) 
      on t1.Id = t2.FkId) t3;
    
    0 讨论(0)
  • 2020-12-16 20:55

    Did you try adding the field to the group by?

    SELECT FkId, COUNT(FkId), a.Name
    FROM B b
    INNER JOIN A a ON a.Id=b.FkId
    GROUP BY FkId,a.Name
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题