在SQL Server中,我有此表:

PlanID  InfoID  Comp    CompName    GuidID  Object
629293  196672  42256   AAA         7       26
629294  196672  42256   AAA         7       24
629295  196672  10000   BBZ         7       21
629296  196673  09023   CCC         7       12
629297  196673  10001   BBY         7       14
629298  196674  09027   DDS         7       16
629299  196674  10004   BBH         1       12

我想按InfoID分组(每个InfoID一行),始终选择CompName != BBx(请注意:BBx始终列在我感兴趣的CompName下,无论字母顺序或Comp值如何):
PlanID  InfoID  Comp    CompName    GuidID  Object
629293  196672  42256   AAA         7       26
629296  196673  09023   CCC         7       14
629298  196674  09027   DDS         7       16

我使用以下代码:
SELECT TOP (10000) MAX (PlanID) AS [PlanID]
  ,MAX (InfoID) AS [InfoID]
  ,MAX (Comp) AS [Comp]
  ,MAX (CompName) AS [CompName]
  ,MAX (GuidID) AS [GuidID]
  ,MAX (Object) AS [Object]

  FROM [Prod].[dbo].[Panel]
  GROUP BY (InfoID)
  order by InfoID desc

当然会导致:
PlanID  InfoID  Comp    CompName    GuidID  Object
629293  196672  42256   BBZ         7       26
629296  196673  10001   CCC         7       14
629298  196674  10004   DDS         7       16

我应该用什么代替MAX(CompName)?
很高兴:还选择链接到'not BBx'CompName的正确Comp。

最佳答案

只需添加一个WHERE子句来过滤不需要包含在分组中的CompName:

WHERE [CompName] NOT LIKE 'BB%'

关于sql-server - SQL Server GROUP BY有条件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48116657/

10-10 20:23