SQL 分组依据的最大值总和
SQL SUM of Maximum Values with Group By
我有一个 table 具有以下结构。
Fruit
Color
Origin
Popularity
Price
Apple
Red
IN
100
100
Apple
Red
IN
90
50
Apple
Red
FR
50
75
Apple
Red
FR
50
80
Apple
Red
20
20
我想获得按水果和颜色分组的总价 (100 + 50 + 75 + 80 + 20),包括按产地分类的最大受欢迎程度总和 (100 + 50 + 20)。以下是预期结果。
Fruit
Color
Popularity
Price
Apple
Red
170
325
我试过用不同的总和进行分组,但给出了错误的结果。
select Fruit, Color, SUM(distinct Popularity), SUM(Price) FROM FRUITS_TABLE Group by Fruit, Color
如果有任何解决方案可以在单个查询中实现此结果,请分享。
我正在使用 MS SQL。
谢谢
我们可以尝试将 ROW_NUMBER
window 函数与子查询一起使用,以通过名为 rn
.
的原始行获得最大流行度
然后使用条件聚合函数求和所有最大流行度
select Fruit,
Color,
SUM(IIF(rn = 1,Popularity,0)) Popularity,
SUM(Price) Price
FROM (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY Fruit, Color,origin ORDER BY Popularity DESC) rn
FROM FRUITS_TABLE
) t1
Group by Fruit, Color
CREATE TABLE Fruit (
Fruit varchar(8) NOT NULL,
Color varchar(8) NOT NULL,
Origin varchar(2) NULL,
Popularity int NOT NULL,
Price int NOT NULL,
-- What is the PK?
)
INSERT INTO Fruit (Fruit, Color, Origin, Popularity, Price)
VALUES
('Apple', 'Red', 'IN', 100, 100),
('Apple', 'Red', 'IN', 90, 50),
('Apple', 'Red', 'FR', 50, 75),
('Apple', 'Red', 'FR', 50, 80),
('Apple', 'Red', NULL, 20, 20)
SELECT Fruit, Color, SUM(PriceSum) AS PriceSum, SUM(PopularityMax) AS PopularityMaxSum
FROM (
SELECT Fruit, Color, Origin,
SUM(Price) AS PriceSum,
MAX(Popularity) AS PopularityMax
FROM Fruit
GROUP BY Fruit, Color, Origin
) T
GROUP BY Fruit, Color
我有一个 table 具有以下结构。
Fruit | Color | Origin | Popularity | Price |
---|---|---|---|---|
Apple | Red | IN | 100 | 100 |
Apple | Red | IN | 90 | 50 |
Apple | Red | FR | 50 | 75 |
Apple | Red | FR | 50 | 80 |
Apple | Red | 20 | 20 |
我想获得按水果和颜色分组的总价 (100 + 50 + 75 + 80 + 20),包括按产地分类的最大受欢迎程度总和 (100 + 50 + 20)。以下是预期结果。
Fruit | Color | Popularity | Price |
---|---|---|---|
Apple | Red | 170 | 325 |
我试过用不同的总和进行分组,但给出了错误的结果。
select Fruit, Color, SUM(distinct Popularity), SUM(Price) FROM FRUITS_TABLE Group by Fruit, Color
如果有任何解决方案可以在单个查询中实现此结果,请分享。
我正在使用 MS SQL。
谢谢
我们可以尝试将 ROW_NUMBER
window 函数与子查询一起使用,以通过名为 rn
.
然后使用条件聚合函数求和所有最大流行度
select Fruit,
Color,
SUM(IIF(rn = 1,Popularity,0)) Popularity,
SUM(Price) Price
FROM (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY Fruit, Color,origin ORDER BY Popularity DESC) rn
FROM FRUITS_TABLE
) t1
Group by Fruit, Color
CREATE TABLE Fruit (
Fruit varchar(8) NOT NULL,
Color varchar(8) NOT NULL,
Origin varchar(2) NULL,
Popularity int NOT NULL,
Price int NOT NULL,
-- What is the PK?
)
INSERT INTO Fruit (Fruit, Color, Origin, Popularity, Price)
VALUES
('Apple', 'Red', 'IN', 100, 100),
('Apple', 'Red', 'IN', 90, 50),
('Apple', 'Red', 'FR', 50, 75),
('Apple', 'Red', 'FR', 50, 80),
('Apple', 'Red', NULL, 20, 20)
SELECT Fruit, Color, SUM(PriceSum) AS PriceSum, SUM(PopularityMax) AS PopularityMaxSum
FROM (
SELECT Fruit, Color, Origin,
SUM(Price) AS PriceSum,
MAX(Popularity) AS PopularityMax
FROM Fruit
GROUP BY Fruit, Color, Origin
) T
GROUP BY Fruit, Color