这是我的数据集
我想找出每个国家/地区最受欢迎的产品。
我已经尝试过了
SELECT
"Country",
MAX(Ft, Vg, Mt),
SUM("Fruit") AS Ft,
SUM("Veg") AS Vg,
SUM("Meat") AS Mt,
FROM
"My_Data_Set"
GROUP BY
("Country");
还有很多其他事情,但无法让任何东西发挥作用。
架构(MySQL v8.0)
CREATE TABLE customers (
CustomerId SERIAL PRIMARY KEY,
Country VARCHAR(255),
Fruit INTEGER,
Veg INTEGER,
Meat INTEGER
);
INSERT INTO customers (CustomerId, Country, Fruit, Veg, Meat) VALUES
(1, 'Spain', 100, 25, 60),
(2, 'USA', 20, 50, 150),
(3, 'India', 25, 20, 15),
(4, 'Germany', 35, 46, 75),
(5, 'Spain', 22, 36, 50),
(6, 'USA', 12, 34, 56),
(7, 'India', 67, 22, 38),
(8, 'Germany', 21, 45, 18);
查询
with cus as (
select
distinct country,
sum(fruit) over(partition by country) as fruit,
sum(veg) over (partition by country) as veg,
sum(meat) over (partition by country) as meat
from
customers
)
select
country,
case when fruit > veg
AND fruit > meat THEN 'fruit' WHEN veg > fruit
AND veg > meat THEN 'veg' WHEN meat > fruit
AND meat > veg THEN 'meat' end as popular_product
from
cus;
国家 | 热门产品 |
---|---|
德国 | 肉 |
印度 | 水果 |
西班牙 | 水果 |
美国 | 肉 |