[英]Group by two columns, take sum, then max
共有三列: Id
(char)、 Name
(char) 和Score
(int)。
首先,我们按Id
和Name
分组,并为每个组添加Score
。 让我们将添加的分数total_score
。
然后,我们按Name
分组,只取total_score
及其对应的Id
和Name
的最大值。 我拥有其他一切,但我很难弄清楚如何获得Id
。 我得到的错误是
select 列表中的“Id”列无效,因为它不包含在聚合 function 或 GROUP BY 子句中。
WITH Tmp AS
(SELECT Id,
Name,
SUM(Score) AS total_score
FROM Mytable
GROUP BY Id,
Name)
SELECT Name, -- Id,
MAX(total_score) AS max_score
FROM Tmp
GROUP BY Name
ORDER BY max_score DESC
WITH Tmp AS
(SELECT Id,
Name,
SUM(Score) AS total_score
FROM Mytable
GROUP BY Id,
Name)
SELECT Name, Id,
MAX(total_score) AS max_score
FROM Tmp
GROUP BY Name,id
ORDER BY max_score DESC
尝试这个。 希望这会有所帮助。
我不确定以下查询的性能,但我们可以使用window functions
从数据partition
中获取maximum
。
SELECT
Id,
Name,
SUM(Score) AS total_score,
MAX(SUM(Score)) OVER(Partition by Name) AS max_score
FROM Mytable
GROUP BY Id, Name;
经测试——
declare @Mytable table (id int, name varchar(10), score int);
insert into @Mytable values
(1,'abc', 100),
(2,'abc', 200),
(3,'def', 300),
(3,'def', 400),
(4,'pqr', 500);
Output -
Id Name total_score max_score
1 abc 100 200
2 abc 200 200
3 def 700 700
4 pqr 500 500
WITH Tmp AS
(
SELECT Id,
Name,
SUM(Score) AS total_score
FROM Mytable
GROUP BY Id,
NAME
)
SELECT Name, Id,
MAX(total_score) AS max_score
FROM Tmp
GROUP BY Name,id
ORDER BY max_score DESC
注意:- 如果我们使用聚合 function 那么我们必须使用其他列作为 Group By....
在您的情况下,您使用 SUM(Score) 作为聚合 function 然后我们使用其他列作为 Group by...
只需按Name
将row_number()
分区添加到您的查询中并获取第一行(按total_score
降序排列)
select *
from
(
-- your existing `total_score` query
SELECT Id, Name,
SUM(Score) AS total_score,
r = row_number() over (partition by Name order by SUM(Score) desc)
FROM Mytable
GROUP BY Id, Name
) d
where r = 1
您可以 select DENSE_RANK()使用total_score
列,然后使用 select 记录Rank = 1
。 当有多个Name
具有相同的total_score
时,这也适用于那些。
WITH Tmp AS
(SELECT Id,
Name,
SUM(Score) AS total_score
FROM Mytable
GROUP BY Id, Name)
SELECT Id,
Name,
total_score AS max_score
FROM (SELECT Id,
Name,
total_score,
DENSE_RANK() OVER (PARTITION BY Name ORDER BY total_score DESC) AS Rank
FROM Tmp) AS Tmp2
WHERE Rank = 1
你也可以试试这个:
select id,name,max(total_score) over (partition by name) max_score from (
select id,name,sum(score) as total_score from YOURTABLE
group by id,name
) t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.