2016-06-05 4 views
1

두 개의 사용자 정의 열을 계산하는 열을 표시하려고합니다.MySQL에서 사용자 정의 열 선택

내가 " 'thetime'필드 목록에서 알 수없는 열"메시지를 얻을이

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(*) 

같은 모양

나는 정의 열 작업 할 수 있습니다 어떻게

?

+2

열을 다시 사용할 수 없습니다. 별명 (예 :'(time from FROM table ...) '에서처럼'thetime'을 즉시 재사용 할 수 없습니다)으로 구성됩니다. 인라인 서브 쿼리가 아닌 조인 된 하위 쿼리에 삽입해야합니다. – Sebas

+0

예, 단지 예일뿐입니다. 죄송합니다. :) – user1071461

+0

한 가지 옵션은 쿼리를 다시 작성하는 것입니다.이 쿼리를 하위 쿼리로 이동 한 다음 외부 선택 문의 문에 액세스 할 수 있습니다. 다른 옵션이있을 수 있지만 추가 정보를 제공해야합니다. – sgeddes

답변

2

당신은 그 이후 열 자체가 아니라 별칭을 사용하는 것을해야 액세스 할 수 없습니다

같은
SELECT COUNT(*) as amount, 
`time` as thetime, 
(`time`/amount) as average 
FROM table WHERE.. 

(OR)이 편집 한 게시물 당

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