简体   繁体   English

选择具有最大值的唯一行(有条件)

[英]Selecting unique rows with maximum values (with conditions)

With the table and data below I am trying to get the highest effective_from values that are less than the current timestamp, per unique brand / model combination - effectively the current price per item. 使用下面的表格和数据,我试图通过每个唯一的brand / model组合,从小于当前时间戳的最高effective_from获取值-实际上是每件商品的当前价格。

CREATE TABLE things
(`id` int, `brand` varchar(1), `model` varchar(5), `effective_from` int, `price` int);

INSERT INTO things
(`id`, `brand`, `model`, `effective_from`, `price`)
VALUES
(1, 'a', 'red', 1402351200, 100),
(2, 'b', 'red', 1402351200, 110),
(3, 'a', 'green', 1402391200, 120),
(4, 'b', 'blue', 1402951200, 115),
(5, 'a', 'red', 1409351200, 150),
(6, 'a', 'blue', 1902351200, 140),
(7, 'b', 'green', 1402358200, 135),
(8, 'b', 'blue', 1902358200, 155),
(9, 'b', 'red', 1902751200, 200),
(10, 'a', 'red', 1908351200, 210),
(11, 'a', 'red', 1402264800, 660);

So far I have managed to get the row I'm looking for when I add conditions for a specific brand / model combination, but don't know how to fetch the current prices for all unique row combinations. 到目前为止,当我为特定的brand / model组合添加条件时,我已经设法找到了要查找的行,但是不知道如何获取所有唯一行组合的当前价格。

SELECT *
FROM things
WHERE effective_from<UNIX_TIMESTAMP()
AND brand='a'
AND model='red'
ORDER BY effective_from DESC
LIMIT 1;

If the current timestamp was 1402404432 the results should be as follows: 如果当前时间戳为1402404432则结果应如下所示:

(1, 'a', 'red', 1402351200, 100),
(3, 'a', 'green', 1402391200, 120),
(2, 'b', 'red', 1402351200, 110),
(7, 'b', 'green', 1402358200, 135),

I guess you're after this. 我想你是在追求这个。 Advise if otherwise... 如有其他建议...

SELECT x.*
  FROM things x
  JOIN 
     ( SELECT brand
            , model
            , MAX(effective_from) max_effective_from 
         FROM things 
        WHERE effective_from <= UNIX_TIMESTAMP() 
        GROUP 
           BY brand
            , model
     ) y 
    ON y.brand = x.brand 
   AND y.model = x.model 
   AND y.max_effective_from = x.effective_from;
+------+-------+-------+----------------+-------+
| id   | brand | model | effective_from | price |
+------+-------+-------+----------------+-------+
|    1 | a     | red   |     1402351200 |   100 |
|    2 | b     | red   |     1402351200 |   110 |
|    3 | a     | green |     1402391200 |   120 |
|    7 | b     | green |     1402358200 |   135 |
+------+-------+-------+----------------+-------+

SELECT UNIX_TIMESTAMP();
+------------------+
| UNIX_TIMESTAMP() |
+------------------+
|       1402404432 |
+------------------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM