简体   繁体   中英

Is it possible to conditionally select a column value based on another column's value in MySQL

I have a query where I use a CTE to get data from a huge table and aggregate values from the records and then use a query to further manupulate the data that i have. The table I have looks similar to this

桌子

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);

The query I use is like this.

    WITH t AS (
    SELECT
       Month,
       SUM(Sales) as Sales,
       AVG(Discount) as Discount
       from table
    WHERE
       Product = 'P1'
    GROUP BY Month
    )
    Select * from t

Now, I want to get the Discount which appears in the maximum number of stores for this product in each month. The effective result I want is as follows, as I would want the sales for the Product added in all stores, hence 620 for Jan, but show the 5 as Discount since it is the available in most stores in Jan.

结果

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM