通过某种逻辑从连接表中获取最大值

时间:2015-05-28 13:26:25

标签: sql postgresql inner-join

这是我的表关系:

tbl_product
-----------
product_id

tbl_product_price
-----------------
price_id
price_product_id (FK)
price_normal 
price_discount
price_disc_valid_from_date 
price_disc_valid_to_date

我想查询tbl_product,按其最高价DESC排序,必须首先验证。如果折扣日期仍然有效(price_disc_valid_from_dateprice_disc_valid_to_date之间的当前日期),则获取price_discount。如果无效,请获取price_normal。在此之后,我需要获得最高价格(来自price_discountprice_normal),然后按最高价格订购。

大多数问题如this只是如何选择最大列,而不是首先在连接表上进行验证。

我的问题是,该查询的postgres sql语句是什么?感谢

[编辑]

我坚持从表格tbl_product_price中选择最高价格,但不知道如何加入tbl_product

SELECT 
    pr.price_id, pr.product_price_id, 
    CASE WHEN current_date BETWEEN pr.price_disc_valid_from_date AND pr.price_disc_valid_to_date 
        THEN pr.price_discount 
        ELSE pr.price_normal END AS price 
    FROM tbl_product_price pr 
    WHERE pr.price_product_id = 316 
    GROUP BY pr.price_id, pr.price_product_id 
    ORDER BY price DESC 
    LIMIT 1;

2 个答案:

答案 0 :(得分:0)

你能做这样的事吗:

SELECT
    tbl_tbl_product.price_product_id,
    tblMax.MaxPrice
FROM
    tbl_tbl_product
    JOIN
    (
        SELECT
            tbl_product_price.price_product_id, 
            MAX(
                CASE 
                    WHEN now() BETWEEN
                               tbl_product_price.price_disc_valid_from_date 
                               AND tbl_product_price.price_disc_valid_to_date
                    THEN tbl_product_price.price_discount
                    ELSE tbl_product_price.price_normal
                END
            ) AS MaxPrice  
        FROM
            tbl_product_price
        GROUP BY
            tbl_product_price.price_product_id
    ) as tblMax
    ON tblMax.price_product_id=tbl_tbl_product.product_id
ORDER BY
    tblMax.MaxPrice DESC

答案 1 :(得分:0)

如果我理解您的逻辑,此查询应返回按产品的最高价格订购的产品:

SELECT
  tp.product_id
FROM
  tbl_product tp INNER JOIN tbl_product_price tpp
  ON tb.product_id = tpp.price_product_id
GROUP BY
  tp.product_id
ORDER BY
  MAX(CASE WHEN current_date BETWEEN tpp.price_disc_valid_from_date
                             AND tpp.price_disc_valid_to_date THEN
      tpp.price_discount
    ELSE
      tpp.price_normal END) DESC