[英]Is it possible to conditionally select a column value based on another column's value in MySQL
我有一个查询,我使用 CTE 从一个巨大的表中获取数据并从记录中聚合值,然后使用查询来进一步处理我拥有的数据。 我的表看起来与此类似
CREATE TABLE `fact_data` (
`product` varchar(20),
`location` varchar(20),
`month` varchar(20),
`sales` bigint(20) DEFAULT 0,
`discount` bigint(20) DEFAULT 0
);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L1','Jan',104,5);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L2','Jan',88,10);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L3','Jan',97,15);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L4','Jan',106,5);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L5','Jan',108,10);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L6','Jan',117,5);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L1','Feb',85,5);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L2','Feb',116,10);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L3','Feb',89,15);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L4','Feb',92,5);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L5','Feb',98,10);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L6','Feb',119,15);
INSERT INTO table
(product, location, month, sales, discount) VALUES('P1','L7','Feb',112,10);
我使用的查询是这样的。
WITH t AS (
SELECT
Month,
SUM(Sales) as Sales,
AVG(Discount) as Discount
from table
WHERE
Product = 'P1'
GROUP BY Month
)
Select * from t
现在,我想获得每月出现在该产品的最大商店数中的折扣。 我想要的有效结果如下,因为我希望在所有商店中添加产品的销售额,因此 1 月份为 620,但显示 5 为折扣,因为它在 1 月份在大多数商店都可用。
尝试这个:
WITH Level1 AS (
select count(*) as CountOfDiscount, month, discount
from fact_data
group by month, discount
),
Level2 AS (
SELECT Month, Discount
FROM Level1
WHERE CountOfDiscount = (SELECT MAX(CountOfDiscount) FROM Level1 AS A WHERE
A.Month = Level1.Month)
)
SELECT Level2.Month, SUM(Sales) AS SumOfSales, Level2.Discount
FROM Level2
JOIN fact_data
ON Level2.Month = fact_data.Month
GROUP BY LEvel2.Month, Level2.Discount
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.