我正在尝试编写一个存储过程来从数据库中提取一些聚合统计信息。
我想修改程序以允许动态选择列。
我的第一个想法是使用Case或IF语句来选择不同的列
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//
现在我不认为案例陈述是为了这个目的,目前它不起作用......是否有可能实现上述目标?
仅供参考 - 我完全清楚我可以选择两列,但我不希望将这两列都暴露给我的网络应用。
答案 0 :(得分:0)
更改此
CASE
WHEN buySell = 'Buy' THEN AVG(salesTransactions.BuyPrice) AS AveragePrice,
WHEN buySell = 'Sell' THEN AVG(salesTransactions.SellPrice) AS AveragePrice,
END CASE;
到
CASE buySell
WHEN 'Buy' THEN AVG(salesTransactions.BuyPrice)
WHEN 'Sell' THEN AVG(salesTransactions.SellPrice)
END AS AveragePrice,
最后它应该是这样的:
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//
我修复了一些语法错误。