SQL:如何每天选择价格最高的二手物品

时间:2019-07-15 06:28:29

标签: sql sql-server greatest-n-per-group

我需要产生一个查询,该查询将为我提供当天价格最高的二手产品,该日当天售出的产品总价超过200。

SELECT *, max(price)
FROM products
WHERE products.`condition` = 'used' and products.price > 200
GROUP BY date_sold

这是我的产品表http://prntscr.com/of3hjd

3 个答案:

答案 0 :(得分:0)

您可以尝试使用价格大于200个按date_sol组的总和的联接

    select  m.date_sold, max(m.price)
    from my_table m 
    inner join (
        select date_sold, sum(price)
        from my_table 
        group by date_sold
        having sum(price)>200 
    ) t on t.date_sold = m.date_sold 
    group by  m.date_sold

答案 1 :(得分:0)

您可以为此使用窗口功能:

select p.*
from (select p.*,
             sum(price) over (partition by date_sold) as sum_price,
             row_number() over (partition by date_sold, condition order by price desc) as seqnum
      from products p
     ) p
where sum_price > 200 and
      condition = 'used' and
      seqnum = 1;

答案 2 :(得分:-1)

SELECT *, max(price) FROM products
where products.`condition` = 'used' and sum(products.price) > 200
GROUP BY day(date_sold)