Mysql - 在价格表中选择低于,等于或高于的数量

时间:2012-06-12 16:30:20

标签: mysql sql

我有一个存储各种产品价格的表格,如果我的价格低于,高于或等于同一天的其他记录,我想知道如何进行查询返回。所有包含idmonitor零的记录只是意味着这是我的价格,我会在同一天与其他记录进行比较。

id | idmonitor | idproduct | price | date
1  | 0         | 5         | 42.00 | 2012-06-01
2  | 1         | 5         | 45.00 | 2012-06-01
3  | 2         | 5         | 50.00 | 2012-06-01
4  | 0         | 6         | 22.00 | 2012-06-01
5  | 1         | 6         | 24.00 | 2012-06-01
6  | 2         | 6         | 26.00 | 2012-06-01
7  | 0         | 5         | 40.00 | 2012-06-03
8  | 1         | 5         | 40.00 | 2012-06-03
9  | 2         | 5         | 40.00 | 2012-06-03
10 | 0         | 6         | 30.00 | 2012-06-03
11 | 1         | 6         | 20.00 | 2012-06-03
12 | 2         | 6         | 10.00 | 2012-06-03

我想查询回复一些像:

date       | below | equal | above
2012-06-01 | 2     | 0     | 0
2012-06-02 | 2     | 0     | 0
2012-06-03 | 0     | 1     | 1

我正试图让这个查询已经过了几天。

2 个答案:

答案 0 :(得分:2)

这样的东西虽然不是性能方面最好的查询,但可能会有这个诀窍:

select aux.date,
       SUM(aux.below) as 'below',
       SUM(aux.equal) as 'equal',
       SUM(aux.above) as 'above'
from
(
   select t1.date,
          t1.idproduct,
          (select count(1) from tablename t2 where t2.date = t1.date and t2.idproduct = t2.idproduct and t2.price > t1.price and t2.idmonitor <> 0) as 'below',
          (select count(1) from tablename t3 where t3.date = t1.date and t3.idproduct = t3.idproduct and t3.price = t1.price and t3.idmonitor <> 0) as 'equal',
          (select count(1) from tablename t4 where t4.date = t1.date and t4.idproduct = t4.idproduct and t4.price < t1.price and t4.idmonitor <> 0) as 'above',
   from tablename t1
   where t1.idmonitor = 0
) aux
group by aux.date

请注意,它来自内存,我可能会遗漏一些东西。

答案 1 :(得分:1)

我已根据idmonitor = 0对此进行了编辑以获得基本价格。我有一个针对我的本地数据库的版本,但你的字段名称不同,所以我可能有一两个错字。

select date, 
  sum(equal_price) as equals,
  sum(above_price) as above,
  sum(below_price) as below from (
select date,
  if (price = base_price, 1, 0) as equal_price,
  if (price > base_price, 1, 0) as above_price,
  if (price < base_price, 1, 0) as below_price
  from orders
  join (select 
    date as base_date, 
      price as base_price
     from orders where idmonitor = 0) as base_price on base_price.base_date = date) as counts
     group by date