奥吉表
number name price month year
152 cheese 25 10 12
153 yogurt 12 10 12
152 cheese 22 11 12
153 yogurt 15 11 12
154 apples 30 11 12
我目前有以下查询,它比较两个月之间的行。
select a.price as p1, b.price as p2, a.distributor, a.number, a.name, (a.price - b.price) as pdiff from ogi a, ogi b where a.number = b.number and a.month = '" . $from_date . "' and b.month = '" . $to_date . "' and a.distributor = '" . $distributor . "'
我现在正在尝试检查上个月是否有一行不存在,以回显“不存在”或类似的内容。
那么,我如何检查上个月是否存在编号为 154 的行(在上表中找到)并回显“不存在” “?
感谢您的帮助!
最佳答案
如果您需要检查每个月与上个月的价格增量,我会这样写您的查询:
SELECT
a.*,
b.price,
case when b.number is not null
then a.price-b.price
else 'did not exist' end as priceDiff
FROM
ogi a left join ogi b
on a.number=b.number
and b.year = case when a.month=1
then a.year-1
else a.year end
and b.month = case when a.month=1
then 12
else a.month-1 end
ORDER BY
a.number, a.month
这会将每个项目的每个价格与上个月的价格进行比较,如果上个月没有行,将返回“不存在”。
请参阅this fiddle .
编辑:我更新了我的答案,我想你正在寻找这个:
SELECT
names.number,
names.name,
a.price pricea,
b.price priceb,
case when a.number is null then 'does not exist'
when b.number is null then 'did not exist'
else a.price-b.price end as priceDiff
FROM
(select distinct number, name
from ogi
where (year=12 and month=11) or
(year=12 and month=10)) names
left join ogi a on names.number=a.number and a.month=11 and a.year=12
left join ogi b on names.number=b.number and b.month=10 and b.year=12
ORDER BY
a.number, a.month
请注意,我没有考虑年份,但如果需要我可以更新查询。
关于php - 检查上个月存在的行(比较两个月之间的数据),其中数字 = 特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14759917/