gpt4 book ai didi

php - 如果匹配查询中的 case 条件,则除以列值

转载 作者:行者123 更新时间:2023-11-29 03:55:51 24 4
gpt4 key购买 nike

我正在尝试将 Accordion 的金额设置为年度或月度状态。

这是 Y = 每年和 M = 每月的列。

period_stats | Amount
Y | 12070.00
M | 2580.00

我想根据金额查询金额,如果 period_statsY 那么金额应该除以 12,如果 period_statsM 然后想得到不除法的直接数量。

I am not a pro in sql, so after some searching i found that i can do it with using case in sql but i didn't get how to use it.

我试过这种方法。如果我使用错误,请纠正我。

select period_stats, CASE period_stats
WHEN 'Y' THEN (amount / 12) as amount_monthly
ELSE amount END as 'amount_monthly' FROM tbale where id = 1;

如果有人知道任何其他技术,那么将不胜感激,我也想知道。


结论:

正确的查询以获得所需的结果。 (通过使用 Sebastian Brosch 的回答)

SELECT 
period_stats,
ROUND(CASE WHEN (period_stats = 'Y') THEN (amount / 12) ELSE amount END, 2)
AS 'amount_monthly'
FROM table
WHERE id = 1;

结果:

amount_monthly
1005

最佳答案

你很接近。您可以使用以下解决方案:

SELECT 
period_stats,
CASE WHEN (period_stats = 'Y') THEN (amount / 12) ELSE amount END AS 'amount_monthly'
FROM table
WHERE id = 1;

demo: http://sqlfiddle.com/#!9/1521ad/2/0

上面的查询使用了以下语法:

CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END

source: https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case


要仅显示两位小数,您可以使用 TRUNCATE (没有舍入)或 ROUND (四舍五入)。

使用TRUNCATE的解决方案:

SELECT 
period_stats,
TRUNCATE(CASE WHEN (period_stats = 'Y') THEN (amount / 12) ELSE amount END, 2) AS 'amount_monthly'
FROM table
WHERE id = 1;

使用ROUND的解决方案:

SELECT 
period_stats,
ROUND(CASE WHEN (period_stats = 'Y') THEN (amount / 12) ELSE amount END, 2) AS 'amount_monthly'
FROM table
WHERE id = 1;

关于php - 如果匹配查询中的 case 条件,则除以列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45476050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com