在group by子句中覆盖文本

时间:2018-05-16 12:40:19

标签: sql tsql

我有一个大型数据表,其中的描述一直输入不一致。我试图找出如何在查询中包含此字段,并仍然对记录进行分组,即使描述不匹配也是如此。在下面的示例中,我不一定需要最长的描述,即使结果返回任何描述恰好是第一个没问题。提前谢谢!

SELECT PartNumber, Description, Sum(TotQtySold), year
From partsTable
GROUP BY PartNumber, Description, year

PartNumber|Description|TotQtySold|year
ABC123    |Repair Kit |5     |2007
ABC123    |kit        |3     |2007
ABC123    |Repair kit |8     |2007

Desired Result
ABC123    |Repair Kit |16    |2007

2 个答案:

答案 0 :(得分:2)

该列不要GROUP BY。相反,SELECT该列的MAX() ...

SELECT PartNumber, MAX(Description), Sum(TotQtySold), year
From partsTable
GROUP BY PartNumber, year

答案 1 :(得分:1)

只需从Description子句移除GROUP BY并使用min/max或使用subquery代替

select PartNumber, 
       (select top 1 Description 
        from table 
        where PartNumber = t.PartNumber and 
              year = t.year
        order by Description desc) as Description, -- remove order by clause if you want whatever Description
       Year
from table t
group by PartNumber, year;

但是,我不建议在Description子句中使用具有长描述的GROUP BY列。