1

小木桌

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 的行在上表中找到)并回显“不存在”?

谢谢您的帮助!

4

3 回答 3

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

这会将每个项目的每个价格与上个月的价格进行比较,如果上个月没有行,将返回“不存在”。

请看这个小提琴

编辑:我更新了我的答案,我想你正在寻找这个:

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

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

于 2013-02-07T20:32:15.253 回答
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'

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

于 2013-02-07T20:26:36.020 回答
0

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

SELECT * 
FROM table 
WHERE id NOT IN 
    (
        SELECT id 
        FROM table 
        WHERE created < var_containing_first_of_current_month
    )
于 2013-02-07T20:32:18.663 回答