2012-06-12 51 views
1

我有一張表,用於存儲各種產品的價格,並希望知道如何執行查詢以返回如果我的價格低於,高於或等於另一個記錄在同一天。所有包含idmonitor零的記錄只是表示這是我的價格,我會在同一天與其他記錄進行比較。Mysql - 在下面選擇計數,等於或高於價格表

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 

我試圖讓這個查詢已經天。

+1

到目前爲止您的查詢是什麼? –

+0

您是否想將價格與特定日期的平均價格進行比較? –

+0

@BrianHoover不,他想比較idmonitor = 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 

注意,它從內存的,我可能失去了一些東西。

+0

它工作。如何修改查詢以顯示第二天的結果作爲第一天的結果,因爲第二天未插入?加入日曆表? – adrianogf

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 
+0

@adrianogf - 我不明白這個問題。 –