0

如何选择第 1 列中的最后一个值和第 2 列最后 5 行中的最大值并将它们合并在一起?

对于这样的表:

Column_1      Column_2       Timestamp
5             3000           2013-07-31 12:00:00
3             1000           2013-07-31 11:00:00
6             2000           2013-07-31 10:00:00
2             4000           2013-07-31 09:00:00
1             5000           2013-07-31 08:00:00

结果应该是:

Column_1      Column_2
5             5000

我的查询是这样的:

select COLUMN_1 from table_A order by Timestamp desc LIMIT 1
UNION
select MAX(COLUMN_2) from (select COLUMN_2 from table_A order by Timestamp desc LIMIT 0,5) as T1;

它向我抛出错误:错误 1221(HY000):UNION 和 ORDER BY 的使用不正确

请帮忙。谢谢。

4

3 回答 3

2

I totally agree with @juergen d, but if you want to do this anyway you can do this using two correlated subquery in the same query like this:

SELECT (select COLUMN_1 
from table1 
order by Timestamp desc LIMIT 1) AS Column_1,
(select MAX(COLUMN_2) 
 from 
 (
   select COLUMN_2 
   from table1 
   order by Timestamp desc 
   LIMIT 0,5
  ) as T1) AS Column_2
FROM table1
LIMIT 1;
于 2013-07-31T10:12:30.840 回答
1

You're getting UNION error because your selects don't have the same column headers. To be able to use UNION, your two parts have to have the same column headers, but you have COLUMN_1 and COLUMN_2

于 2013-07-31T10:12:45.623 回答
1

既然这两个选择不是很密切相关 - 为什么不做两个单独的选择?!

它在代码中更容易和更清晰。

于 2013-07-31T10:10:26.767 回答