【问题标题】:Conditions in SQL to provide correct outputSQL 中提供正确输出的条件
【发布时间】:2012-02-20 18:49:06
【问题描述】:

我正面临一个棘手的问题。

我需要让下表提供唯一数据,当我的意思是唯一时,它只需要一个 customerID 记录。价格也必须是最大值。

--------------------------------------
customerID, basketID, orderID, productID, price
--------------------------------------
1, 1001, 101, 24, 15
1, 1001, 102, 24, 15
1, 1001, 103, 28, 19

您可以看到,即使它们是相同的购物篮、客户和产品,orderID 也会增加 1。这显示了产品的数量。

希望我需要一条记录,其中 1 作为客户 ID,但显示最高价格。

--------------------------------------
customerID, basketID, orderID, productID, price
--------------------------------------
1, 1001, 103, 28, 19

查询必须以select开头,不能使用Order By,因为我们使用的系统不支持。

如果有人对我应该做什么有丝毫线索,那就太好了。

谢谢。

【问题讨论】:

  • 你的系统怎么会不支持ORDER BY?没有它,您没有保证任何行顺序。

标签: sql select unique denormalization


【解决方案1】:

尝试以下方法:

SELECT customerID, basketID, orderID, productID, price
FROM TABLENAME t
WHERE price = (select max(price) from TABLENAME t2 where t.customerID = t2.customerID)

【讨论】:

  • 但我认为它会以最高价格获得多个客户的记录
  • 但我认为他想要每个客户/购物篮的最高价格,而不是整体价格。
【解决方案2】:

如果您有多个 customerID/basketID,以下方法将起作用:

select t1.* from tablename t1
inner join (select customerID, basketID, max(Price) as Price from tablename
group by customerID, basketID) t2 on t1.customerID = t2.customerID and t1.basketID = t2.basketID and t1.Price = t2.Price 

【讨论】:

    【解决方案3】:

    试试这个:

    SELECT * FROM t 
     WHERE (customer_id, price) IN (SELECT customer_id, MAX(price)
                                      FROM t GROUP BY customer_id)
    

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2021-06-15
      • 1970-01-01
      • 2021-06-29
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2012-04-06
      相关资源
      最近更新 更多