如何使用SQL对产品进行价格比较

时间:2018-08-11 00:36:55

标签: mysql sql

我有以下数据:

product_id       store           price
1                itunes          8.99
1                google          9.99
1                amazon          10.00
2                itunes          10.00
2                google          4.99

如何查询所有product_id的价格,这些价格在iTunes上的价格高于Google。在上面的示例中,将是:

product_id      itunes      google
2               10.00       4.99

到目前为止,我有一个汇总查询可以执行此操作,但是却陷入了价格比较部分:

SELECT 
  product_id, 
  GROUP_CONCAT(case when platform_type_id='itunes' then price end) itunes,
  GROUP_CONCAT(case when platform_type_id='google' then price end) google
 FROM 
  table GROUP BY product_id

查询不完整,但这是我要去的方向。正确的方法是什么?

3 个答案:

答案 0 :(得分:3)

另一种可能的解决方案是使用INNER JOIN将每个iTunes产品与相应的Google产品(其中Google价格更便宜)连接起来。

SELECT ti.product_id,
       ti.price itunes,
       tg.price google
       FROM elbat ti
            INNER JOIN elbat tg
                       ON tg.product_id = ti.product_id
                          AND tg.price < ti.price
       WHERE ti.store = 'itunes'
             AND tg.store = 'google';

答案 1 :(得分:1)

您可以在having中使用比较。

SELECT 
  product_id, 
  MAX(CASE WHEN store='itunes' THEN PRICE END) as itunes,
  MAX(CASE WHEN store='google' THEN PRICE END) as google
FROM table 
GROUP BY product_id
HAVING MAX(CASE WHEN store='itunes' THEN PRICE END) >  MAX(CASE WHEN store='google' THEN PRICE END)

编辑:

您可以将HAVING子句简化为:

HAVING itunes > google

答案 2 :(得分:-1)

不过在Postgres中:

with itunes as (select productid, price from table_ where store='itunes'),
google as (select productid,price table_ where store='google')

Select itunes.productid, itunes.price as "price", google as "price"
From itunes,google
Where itunes.price>google.price