如果特定item_id存在两个或更多非零值,我只想计算值的AVG。如果不存在两个或多个非零值,我不想计算AVG。
当前的SQL如下。也许首先应该有一个if子句?......任何想法?
SELECT AVG( days_since ) AS days_out
FROM (
SELECT days_since
FROM user_123
WHERE item_id = 645
AND days_since <> 0
ORDER BY id DESC
LIMIT 5
) AS recent
似乎可以使用If子句;
IF SELECT COUNT (*), item_id, days_since >= 2
where days_since <>0, then perform AVG...
答案 0 :(得分:2)
怎么样:
SELECT AVG(days_since) AS days_out
FROM User_123
WHERE Item_ID = 645
AND Days_Since <> 0
HAVING COUNT(*) > 1
我不确定ORDER BY和LIMIT条款的用途,因此您必须调整答案以重新表达它们所隐含的条件。
如何在重新应用Order By和Limit时保持其正常工作。使用它们以便在平均值计算中仅使用最近的5个条目。
SELECT AVG(days_since) AS days_out
FROM (SELECT days_since
FROM User_123
WHERE Item_ID = 645
AND Days_Since <> 0
ORDER BY ID DESC
LIMIT 5
) AS u
HAVING COUNT(*) > 1;