gpt4 book ai didi

php - 项目名称相同的两个数值之间的差异

转载 作者:行者123 更新时间:2023-11-29 06:53:06 25 4
gpt4 key购买 nike

我有一个名为“items”的表

id       month       year       **itemname**       distmoney
1 12 2012 chicken 20
2 12 2012 pork 15
3 11 2012 chicken 21
4 11 2012 pork 15

我试图找出两个月之间同一商品名称的“distmoney”之间的区别。

例子:

ID 1,元素名称鸡。第 12 个月的 distmoney 是 20,而第 11 个月的 distmoney 是 21。我希望能够计算 id=1,itemname=chicken 的 1 的差值

现在我有 php 代码来计算两个数字之间的差值,但我很难弄清楚如何获取上个月的 distmoney。

<?php foreach($rows as $row): ?>
<?php $number1 = htmlentities($row['distmoney']) ?>
<?php endforeach; ?>
<?php
$number1 = $row['distmoney'];
$number2 = ????????; // THIS NEEDS TO BE THE PREVIOUS MONTH DISTMONEY VALUE
if ($number1 <= $number2) {
$difference = "(Price Lowered) Price difference of $";
$result = $number2 - $number1;
$percent = round(100.0*($number2-$number1)/$number1);
echo $difference; echo $result; echo $percent; echo "%";
} elseif ($number1 > $number2) {
$result = $number1 - $number2;
$percent = round(100.0*($number2/$number1-1));
$addition = "(Price Higher) Price difference of $";
echo $addition; echo $result; echo $percent; echo "%";
}

?>

最佳答案

如果您想在 SQL 中执行此操作,则可以转换列中的数据,然后获取差异:

select 
itemname,
max(case when month = 12 and year = 2012 then distmoney else 0 end) Dec2012,
max(case when month = 11 and year = 2012 then distmoney else 0 end) Nov2012
from yourtable
group by itemname

参见 SQL Fiddle with Demo

查询结果为:

| ITEMNAME | DEC2012 | NOV2012 |
--------------------------------
| chicken | 20 | 21 |
| pork | 15 | 15 |

关于php - 项目名称相同的两个数值之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329615/

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