我试过这个,它至少适用于 mySQL。
SELECT avg(viewer) FROM log GROUP BY CASE p_id WHEN 5 THEN 1 ELSE p_id END;
编辑:当使用名为 'aliases' 的别名表和字段 'alias_from_id' 和 'aliased_as' 时:
SELECT
CASE ISNULL((SELECT aliased_as FROM aliases WHERE (alias_from_id = log.pid)))
WHEN 1 THEN log.pid ELSE aliased_as END AS the_id,
SUM(value) AS value_sum
FROM log
LEFT JOIN aliases ON (alias_from_id = pid)
GROUP BY
CASE ISNULL((SELECT aliased_as FROM aliases WHERE (alias_from_id = log.pid)))
WHEN 1 THEN log.pid ELSE aliased_as END
我已经用 mySQL 对此进行了测试,它就像一个魅力。可能可以稍微简化一下这个 SQL 查询,但这是我目前能做的最好的:)
Edit2:将 ISNULL 更改为相应的 SQLiteIFNULL
函数
SELECT
IFNULL((SELECT aliased_as FROM aliases WHERE (alias_from_id = log.pid)), log.pid) AS the_id,
SUM(value) AS value_sum
FROM log
LEFT JOIN aliases ON (alias_from_id = pid)
GROUP BY
IFNULL((SELECT aliased_as FROM aliases WHERE (alias_from_id = log.pid)), log.pid)
我不知道 SQLite 是否支持 AS 关键字,如果不支持则删除该关键字 - 功能应该是相同的。