我正在尝试创建一个查询来列出特定类型图书的平均价格,但前提是平均价格高于500.
这是我目前的查询:
SELECT TYPE,
IF(Avg(pages) > 500, Round(Avg(pages)), NULL) AS "Average Pages"
FROM titles
GROUP BY TYPE;
这给了我这个:
+------------+---------------+
| type | Average Pages |
+------------+---------------+
| biography | NULL |
| children | NULL |
| computer | 1226 |
| history | NULL |
| psychology | 512 |
+------------+---------------+
这当然包括NULL值,当我试图实现这个时:
+------------+---------------+
| type | Average Pages |
+------------+---------------+
| computer | 1226 |
| psychology | 512 |
+------------+---------------+
虽然我不确定这样做的最好方法。我已经搞乱了WHERE语句,但没有运气。
答案 0 :(得分:1)
对于聚合函数,您可以使用
过滤结果 $row = $this->baseClass->db->pdoQuery('SELECT SUM(user_have_group.user_group = 2 ) AS boosters , count(user.id ) AS created_accounts FROM `user` LEFT JOIN `user_have_group` ON user_have_group.user_id = user.id ')->result();
答案 1 :(得分:1)
你走了:
SELECT type, AVG(pages) AS "Average Pages"
FROM titles
GROUP BY type
HAVING AVG(pages) >= 500;
答案 2 :(得分:0)
您是否曾尝试IS NOT NULL
这样:
SELECT
`type`,
IF(Avg(`pages`) > 500, Round(Avg(`pages`)), NULL) AS `avg_pages`
FROM `titles`
WHERE `avg_pages` IS NOT NULL
GROUP BY `type`;