1

我有一个存储各种产品价格的表,并且想知道如果我的价格低于、高于或等于同一天的其他记录,如何进行查询以返回。所有包含 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

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

4

2 回答 2

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

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

于 2012-06-12T16:40:25.997 回答
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
于 2012-06-12T16:49:17.177 回答