MySQL查询返回多行不同列的MIN()和MAX()

时间:2015-06-20 05:07:25

标签: mysql

我目前有一个价格表,其中包含以下布局:

stringValue.replace(/\n/g, '<br/>')

我需要一个SQL查询,它会为每个代号提供一行代码。每行必须包含代号,然后是最低价格(以及该价格的相关折扣和时间戳),以及最新时间戳(再次包含该时间戳的相关价格和折扣)

期望的输出:

id    codename    price    discount     timestamp
1     1234        599      50           2015-06-10 00:00:00
2     1234        1099     25           2015-06-11 00:00:00
3     3344        199      33           2015-06-12 00:00:00
4     5565        2499     0            2015-06-13 00:00:00
5     5565        1299     50           2015-06-14 00:00:00

编辑:所以我已经到了可以获得2个单独查询的位置,一个获得MIN(价格)的行,第二个获得每个代号的MAX(时间戳)行。

现在我需要做的是将它们连接在一起,以便它们都在同一行(按代号分组),如上例所示。

SQL Fiddle of 2 queries

2 个答案:

答案 0 :(得分:0)

尝试以下,

Select codename, minPrice, minDis, minTime, latestPrice, latestDis,  latestTime  from 
(
    Select T_Low.codename, minPrice, minDis, minTime, T_Latest.latestPrice, T_Latest.latestDis,  T_Latest.latestTime from
    (
        select * from (
    select row_number() over(partition by codename order by codename, price) row_id, codename, price as minPrice, discount as minDis, timestamp as minTime from 
        (
        select codename, discount, timestamp , min(price) as price from prices 
        group by codename, discount, timestamp
        )T
        ) T1 
        where row_id = 1
    ) T_Low
    left join 
    (
        select * from (
    select row_number() over(partition by codename order by codename, timestamp desc) row_id, codename, price as latestPrice, discount as latestDis, timestamp as latestTime from 
        (
        select codename, discount, timestamp , min(price) as price from prices 
        group by codename, discount, timestamp
        )T
        ) T1 
        where row_id = 1
    )t_Latest
    ON T_Low.codename= T_Latest.codename and T_Low.row_id = T_Latest.row_id
)T
order by codename

答案 1 :(得分:0)

所以在玩了一些连接之后,我能够将每个代号输出2个查询输出到一行:

SELECT *
FROM
(
  SELECT p.* 
  FROM prices p
  JOIN 
  ( 
    SELECT codename, MIN(price) minPrice
    FROM prices GROUP BY codename
  ) p2
  ON p.price = p2.minPrice AND p.codename = p2.codename
) min
LEFT JOIN
(
  SELECT p.* 
  FROM prices p
  JOIN 
  ( 
    SELECT codename, MAX(timestamp) maxTime
    FROM prices GROUP BY codename
  ) p2
  ON p.timestamp = p2.maxTime AND p.codename = p2.codename
) latest
ON latest.codename = min.codename

我确信查询远非完美,但它确实给了我正在寻找的结果。

SQL Fiddle

如果这有任何严重错误,请告诉我,我可以更新。