开发者

Choose an aggregate function for Group BY in SQL Server

开发者 https://www.devze.com 2023-01-30 06:59 出处:网络
I have a query like this: Select Count(*) as TotalCount, Object2_ID, Object_ID, Object_Description from Table1

I have a query like this:

Select Count(*) as TotalCount, Object2_ID, Object_ID, Object_Description
from Table1 
inner join table2 on...  
Group BY Object2_ID, Object_ID

I can't run this query because the column Object_Description isn't in GROUP BY or under aggregate function. Object_Description is a text column. I need any value of Object_Description. Now I use MAX(Object_Description) because it gives me right results, because Object_Description is the same for each group.

I can use MAX() or MIN() etc. - I will get right results in m开发者_Python百科y query.

The question is - what is the most sufficient way to do this ?

I think that MAX() or MIN() produces small overheads.


You can get Object Description later, after calculation quantity (assumed that description in in table1 and you need get count from Table2):

SELECT Object_Id, Object_Description, Qty
FROM
( 
  SELECT Object_Id, Count(*) Qty
  FROM Table2
  GROUP BY Object_Id
) t 
JOIN Table1 t2 on t2.Object_Id = t.Object_Id
0

精彩评论

暂无评论...
验证码 换一张
取 消