mysql新手,
在一个表(名为tableX的表)下,假设结构如下所示
server date numberofUser
server1 timestamp 3
server2 timestamp 2
server3 timestamp 7
server1 timestamp 2
server2 timestamp 8
server3 timestamp 4
我想收集最后100次出现(所以通过时间戳)但是对于每个时间戳(这意味着对于timestampX(测量所有server1,2,3),我想要服务器1和服务器2的总numberofUser。 / p>
所以欲望输出是
timestamp1 5 (which comes from server1(2) and server2(3) added
timestamp2 24 (which comes from server1(12) and server2(12) added
timestamp3 7 (which comes from server1(3) and server2(4) added
有人可以指出我正确的方向吗?谢谢
我已经获得了所有服务器(服务器1和2)的最后x次出现的总数,如下所示,但是现在我需要按每个时间戳分解
select sum(numberofUser) from (
(select server, date, numberofUser from tableX
where server = 'server1'
order by date limit 10)
union
( select server, date, numberofUser from tableX
where server = 'server2'
order by date limit 10 )) as t
:::::::::::::::::::::::::::::: UPDATE :::::::::::::::: ::
http://sqlfiddle.com/#!9/7bc7f/1
我的计划是
输出我希望看到下面的给定方案
date1 total
1970-01-01 00:00:03 85
1970-01-01 00:00:04 125
答案 0 :(得分:1)
要达到您想要的输出,您必须limit 2
而不是您在问题中提到的100。第二个查询在内部使用派生表,首先强制执行最后一个(限制2),外部查询将结果翻转为按照您显示的顺序排序。
select date1,sum(numOfUsers) as total
from test1
where server in ('server1','server2')
group by date1
order by date1 desc
limit 2;
+---------------------+-------+
| date1 | total |
+---------------------+-------+
| 1970-01-01 00:00:04 | 125 |
| 1970-01-01 00:00:03 | 85 |
+---------------------+-------+
select date1,total
from
( select date1,sum(numOfUsers) as total
from test1
where server in ('server1','server2')
group by date1
order by date1 desc
limit 2
) xDerived
order by date1;
+---------------------+-------+
| date1 | total |
+---------------------+-------+
| 1970-01-01 00:00:03 | 85 |
| 1970-01-01 00:00:04 | 125 |
+---------------------+-------+
xDerived
只是一个别名。即使之后未明确使用,每个派生表都需要别名。无论它看起来多么愚蠢。