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