我想显示一个计算两个自定义列的列。
它看起来像这样
SELECT to_account as account,
SUM(amount) total_claimed,
COUNT(*) as transaction_count,
((SELECT time FROM transactions WHERE to_account = account ORDER BY time DESC LIMIT 1)
- (SELECT time FROM transactions WHERE to_account = account LIMIT 1)) / 3600 as interval_hours,
(transaction_count / interval_hours) as avg_per_hour
FROM transactions
WHERE type='CLAIM' group by to_account ORDER BY COUNT(*)
我收到了消息"未知列'时间'在字段列表"
如何使用自定义列?
答案 0 :(得分:1)
你应该使用列本身而不是别名,因为它不像
那样可以访问SELECT COUNT(*) as amount,
`time` as thetime,
(`time` / amount) as average
FROM table WHERE..
(或)在外部查询中完成它,如
SELECT *, (thetime / amount) as average
FROM (
SELECT COUNT(*) as amount,
(SELECT time FROM table ...) as thetime
FROM table WHERE...)XXX;
根据您编辑的帖子,您再次使用相同的表达式(OR)获取外部查询中的自定义列,如
SELECT *, (transaction_count / interval_hours) as avg_per_hour
FROM (
SELECT to_account as account,
SUM(amount) total_claimed,
COUNT(*) as transaction_count,
((SELECT time FROM transactions WHERE to_account = account ORDER BY `time` DESC LIMIT 1)
- (SELECT `time` FROM transactions WHERE to_account = account LIMIT 1)) / 3600 as interval_hours
FROM transactions
WHERE type='CLAIM'
group by to_account
ORDER BY COUNT(*)
) tbl