![](/img/trans.png)
[英]How to find all (group-based) rows containing MIN/MAX values for a particular column in SQL Server?
[英]How to group rows based on Min value of the column in SQL Server 2008
我正在寻找一种基于列的最小值对行进行分组的方法。 下面是方案。任何帮助将不胜感激。
例如:
我的查询:
从#tmpTable Group BY ID,名称,价格,GroupId,GroupName,密钥中选择ID,名称,SUM(Price)作为价格,GroupId,GroupName,密钥
我试图使用ROW_NUMBER()。根据这一职位,但有问题让所有类似的组ID和ID的SUM(价格)
我的输出是:1测试300 3 G3
VS
预期输出:1测试600 3 G3
提前致谢!
以下是解决我遇到的问题的查询。 我仍在使用Row_Number(),然后汇总Price以获取总和。 (嵌套查询)
最终答案 :
Select Id,
Name,
SUM(Price) As Price,
GroupId,
GroupName
(
Select Id,
Name,
SUM(Price) As Price,
GroupId,
GroupName,
Key,
Row_Number() OVER (PARTITION BY Id, GroupId ORDER BY Key) As rna
From #tmpTable
Group BY Id, Name, Price, GroupId, GroupName, Key
) As A
Where rna = 1
Group BY Id, Name, Price, GroupId, GroupName
Select Id,
Name,
SUM(Price) As Price,
GroupId,
GroupName
(
Select Id,
Name,
SUM(Price) As Price,
GroupId,
GroupName,
Key,
Row_Number() OVER (PARTITION BY Id, GroupId ORDER BY Key) As rna
From #tmpTable
Group BY Id, Name, Price, GroupId, GroupName, Key
) As A
Where rna = 1
Group BY Id, Name, Price, GroupId, GroupName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.