将聚合与行数据进行比较

时间:2011-12-01 08:04:56

标签: mysql sql

我在MySql中有一个与购买库存相关的表。

表格格式如下:

  • itemname(varchar)
  • vendor(varchar)
  • pdate(datetime)
  • 数量(小数)
  • 费率(十进制)
  • 总计(十进制)
  • id(mediumint)(自动增量)
A report is to be generated that must have the following columns

Item     HighestRate     HighestRateDate        LowestRate      LowestRateDate    % difference

--
Item  is the itemname
HighestRate and HighestRateDate are rates at maximum
LowestRate and Date are rates at minimum
%difference is a basic difference percentage between highestrate and lowestrate of a row

我准备了以下查询

SELECT itemname,rate,pdate  from purchases 
group by itemname
having rate = max(rate)
order by itemname

确实生成报告的一半。

然而,因为它需要最低和最高的费率。该报告不完整,打印两份报告使比较困难。

任何帮助都将不胜感激。

三江源

2 个答案:

答案 0 :(得分:2)

到此为止。它不漂亮,但它有效。

select min.itemname, 
       min.rate, 
       min.pdate, 
       max.rate, 
       max.pdate, 
       (max.rate - min.rate)/max.rate as diff 
  from (SELECT p.itemname, 
               p.rate,
               pdate 
          from purchases p, 
               (select itemname, 
                       max(rate) as rate 
                  from purchases 
                 group by itemname) max_values 
         where p.itemname = max_values.itemname 
           and p.rate = max_values.rate
       ) max, 
       (SELECT p.itemname, 
               p.rate,
               pdate 
          from purchases p, 
               (select itemname, 
                       min(rate) as rate 
                  from purchases 
                 group by itemname) min_values 
         where p.itemname = min_values.itemname 
           and p.rate = min_values.rate
       ) min 
  where max.itemname = min.itemname;

答案 1 :(得分:1)

对于此查询,您需要(itemname, rate)上的索引才能非常慢。

如果有两个或更多日期具有相同的最大(或最小)费率,则将选择(或多或少)随机日期。如果您想控制它,请更改ORDER BY rate ASC(例如ORDER BY rate ASC, pdate DESC):

SELECT 
    di.itemname  AS Item
  , maxr.rate    AS HighestRate
  , maxr.pdate   AS HighestRateDate
  , minr.rate    AS LowestRate
  , minr.pdate   AS LowestRateDate
  , (maxr.rate - minr.rate)/maxr.rate        --- calculations
                 AS PrecentDifference
FROM
    ( SELECT DISTINCT itemname
      FROM purchases 
    ) AS di
  JOIN
    purchases AS minr
      ON  minr.id =                          --- I guess this is the PK
          ( SELECT id
            FROM purchases p
            WHERE p.itemname = di.itemname 
            ORDER BY rate ASC
            LIMIT 1
          )
  JOIN 
    purchases AS maxr
      ON  maxr.id =                      
          ( SELECT id
            FROM purchases p
            WHERE p.itemname = di.itemname 
            ORDER BY rate DESC
            LIMIT 1
          )