检查上个月存在的行(比较两个月之间的数据),其中数字=特定值

时间:2013-02-07 19:59:16

标签: php mysql

ogi table

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是否存在在上面的表格中找到)和echo"不存在"?

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

如果您需要检查每个月与上个月的价格差异,我会以这种方式编写您的查询:

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

请注意我不考虑这一年,但如果需要,我可以更新查询。

答案 1 :(得分:0)

使用LEFT JOIN

SELECT a.price AS p1, b.price AS p2, a.distributor, a.number, IFNULL(a.name, 'Does not exist') AS name, (a.price - IFNULL(b.price, 0)) AS pdiff
FROM ogi a
LEFT JOIN ogi b ON b.number = a.number
WHERE a.month = '$from_date' AND b.month = '$to_date' AND a.distributor = '$distributor'

我强烈建议您更改表格结构以使其标准化。

答案 2 :(得分:0)

我相信你所寻找的是内心选择。以下伪查询说明了如何获取当前月份之前不存在的任何数据

SELECT * 
FROM table 
WHERE id NOT IN 
    (
        SELECT id 
        FROM table 
        WHERE created < var_containing_first_of_current_month
    )