Domanda

I am trying to write a stored procedure to pull off some aggregate statistics from a database.

I would like to amend the procedure to allow dynamic selection of columns.

My first thoughts were to use a Case or IF statement to select different columns

DELIMITER//
CREATE PROCEDURE 'procStats'(IN buySell varchar(4))
SELECT 

    CASE 
        WHEN buySell = 'Buy' THEN AVG(salesTransactions.BuyPrice) AS AveragePrice,
        WHEN buySell = 'Sell' THEN AVG(salesTransactions.SellPrice) AS AveragePrice,
    END CASE;

    MONTHNAME(salesTransactions.DateOfTransaction) as TransactionMonth
FROM
    salesTransactions
GROUP BY 
    TransactionMonth
LIMIT 6;
END//

Now I don't think that case statements are intended for this purpose, and it currently doesn't work... Is it possible to achieve the above??

FYI - I am fully aware that i could just select both columns however I do not wish to expose both columns to my web app.

È stato utile?

Soluzione

Change this

CASE 
    WHEN buySell = 'Buy' THEN AVG(salesTransactions.BuyPrice) AS AveragePrice,
    WHEN buySell = 'Sell' THEN AVG(salesTransactions.SellPrice) AS AveragePrice,
END CASE;

to

CASE buySell
    WHEN 'Buy' THEN AVG(salesTransactions.BuyPrice) 
    WHEN 'Sell' THEN AVG(salesTransactions.SellPrice)
END AS AveragePrice,

In the end it should look like this:

DELIMITER//
CREATE PROCEDURE procStats (IN buySell varchar(4))
BEGIN
SELECT 

    CASE buySell
        WHEN 'Buy' THEN AVG(salesTransactions.BuyPrice) 
        WHEN 'Sell' THEN AVG(salesTransactions.SellPrice)
    END AS AveragePrice,

    MONTHNAME(salesTransactions.DateOfTransaction) as TransactionMonth
FROM
    salesTransactions
GROUP BY 
    TransactionMonth
LIMIT 6;
END//

I fixed some more syntax errors.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top