0

我有来自 SELECT 查询的数据行,其中包含一些价格(本例中为三个)。一个是我们的价格,一个是竞争对手 1 的价格,一个是竞争对手 2 的价格。我想添加一个列来显示我们的价格与其他两个价格相比的排名;如果我们的价格是最低的,它会吐出数字 1 如果最高,它会吐出它的数字。

像这样的东西:

Make |  Model  |  OurPrice | Comp1Price  | Comp2Price | Rank |  OutOf
MFG1    MODEL1     350         100           500         2        3
MFG1    MODEL2     50          100           100         1        3
MFG2    MODEL1     100         NULL          50          2        2
MFG2    MODEL2     9999        500           NULL        2        2

- 有时竞争对手的价格会如上所示为 NULL,我相信这就是我的问题所在。我试过 aCASE并且它只在一个竞争对手上有效,但是当我添加一个AND声明时,它会吐出所有的排名NULL。有没有更好的方法通过 MySQL 查询来做到这一点?

SELECT
      MT.MAKE as Make,
      MT.MODEL as Model,
      MT.PRICE as OurPrice,
      CT1.PRICE as Comp1Price,
      CT2.PRICE as Comp2Price,
      CASE
         WHEN MT.PRICE < CT1.PRICE AND MT.PRICE < CT2.PRICE
         THEN 1 END AS Rank
      (CT1.PRICE IS NOT NULL) + (CT2.PRICE IS NOT NULL) + 1 as OutOf
  FROM mytable MT

LEFT JOIN competitor1table as CT1 ON CT1.MODEL = MT.MODEL
LEFT JOIN competitor2table as CT2 ON CT2.MODEL = MT.MODEL

ORDER BY CLASS
4

2 回答 2

1

未测试,但您可以尝试:

SELECT
    a.MAKE AS Make,
    a.MODEL AS Model,
    a.PRICE AS OurPrice
    MAX(CASE WHEN a.compnum = 1 THEN pricelist END) AS Comp1Price,
    MAX(CASE WHEN a.compnum = 2 THEN pricelist END) AS Comp2Price,
    FIND_IN_SET(a.PRICE, GROUP_CONCAT(a.pricelist ORDER BY a.pricelist)) AS Rank,
    COUNT(a.pricelist) AS OutOf
FROM
(
    SELECT MAKE, MODEL, PRICE, PRICE AS pricelist, 0 AS compnum
    FROM mytable

    UNION ALL

    SELECT a.MAKE, a.MODEL, a.PRICE, CT1.PRICE, 1
    FROM mytable a
    LEFT JOIN competitor1table CT1 ON a.MODEL = CT1.MODEL

    UNION ALL

    SELECT a.MAKE, a.MODEL, a.PRICE, CT2.PRICE, 2
    FROM mytable a
    LEFT JOIN competitor2table CT2 ON a.MODEL = CT2.MODEL
) a
GROUP BY
    a.MAKE, a.MODEL
于 2012-07-10T22:42:01.813 回答
0
(CT1.PRICE IS NOT NULL AND CT1.PRICE < MT.PRICE) + (CT2.PRICE IS NOT NULL AND CT2.PRICE < MT.PRICE) + 1 as Rank
于 2012-07-10T20:55:50.750 回答