我在尝试找出以下问题时遇到了问题,甚至不能100%确定是否可以单独从纯mysql查询完成此任务。
我需要选择共享相同ID和类型的行,同时跟踪他们的TimeStamps。
SELECT ObjectId, TimeStamp, Count(ObjectId) As theCount FROM
(Select ObjectId, TimeStamp, RelationType, ObjectType From Table
Group By ObjectId, TimeStamp) As tmp
WHERE RelationType = 'A'
AND ObjectType = 'B'
GROUP By ObjectId
HAVING Count(ObjectId) >= 0 ORDER By theCount DESC
查找和计算足够类似的行数供我选择的部分很容易,但我在下一部分遇到了麻烦。
我需要在中位数TimeStamp之后跟踪所有TimeStamps,并获得高于中位数TimeStamp的那些TimeStamps的平均值。我需要将那些TimeStamps的平均值高于其中位数,以便我可以命令它们进行DESC。
如果我的问题不够明确或有任何问题请发帖,我可以回复评论。我花了很多时间尝试不同的方法来实现我的目标,但我觉得唯一正确的代码是上面发布的查询。
以下代码就是我现在所处的位置。我得到了所有分组项目的平均值,但就像我说我只需要在组中位数之上的TimeStamps的平均值。
SELECT * FROM( SELECT ObjectId, PostDate, Count(ObjectId) AS Count, AVG(TimeStamp) AS Average
FROM (Select ObjectId, TimeStamp, RelationType, ObjectType
FROM Relations Group By ObjectId, TimeStamp
) As tmp
WHERE RelationType = 'A' AND ObjectType = 'B'
GROUP By ObjectId HAVING Count(ObjectId) >= 1
AND AVG(TimeStamp) > MIN(TimeStamp)
ORDER By Count DESC ) AS tmp2 ORDER BY Average DESC, Count LIMIT 10
RETURNS:
ObjectId: 112717 // Count: 2 // Average: 20151030188390.5
ObjectId: 166047 // Count: 4 // Average: 20151023363026.25
ObjectId: 166312 // Count: 3 // Average: 20151022171454.332
ObjectId: 166309 // Count: 2 // Average: 20151022170765.5
ObjectId: 166307 // Count: 2 // Average: 20151022170765.5
ObjectId: 165163 // Count: 2 // Average: 20151021188390.5
ObjectId: 133214 // Count: 2 // Average: 20151021188388
ObjectId: 165164 // Count: 2 // Average: 20151021188388
ObjectId: 165831 // Count: 2 // Average: 20151021184532.5
ObjectId: 165822 // Count: 2 // Average: 20151021184532.5