p304의 실습11에 대해 문의
2013-02-06
|
by baramosk
1812
실습 11에 대해 여러 방법을 해보았습니다.
-- WITH CTE 구문을 활용하기
with tmpbuy(tuserid, total) as(
select userID, sum(amount*price) as total from buyTbl
group by userID)
select u.userID, u.name, t.total, userclass=
case
when(t.total>=1500) then 최우수고객
when(t.total>=1000) then 우수고객
when(t.total>=1) then 일반고객
else 유령고객
end
from userTbl u
left join tmpbuy t on u.userID=t.tuserid
order by t.total desc, u.userID
go
-- alias 사용하기
select u.userID, u.name, SUM(amount*price) as total,
case
when(sum(amount*price)>=1500) then 최우수고객
when(sum(amount*price)>=1000) then 우수고객
when(sum(amount*price)>=1) then 일반고객
else 유령고객
end as userclass
from buyTbl b
right join userTbl u on b.userID=u.userID
group by u.userID, u.name order by sum(amount*price) desc, u.userID
-- 새로운 열을 쓰기
select u.userID, u.name, SUM(amount*price) as total, userclass=
case
when(sum(amount*price)>=1500) then 최우수고객
when(sum(amount*price)>=1000) then 우수고객
when(sum(amount*price)>=1) then 일반고객
else 유령고객
end
from buyTbl b
right join userTbl u on b.userID=u.userID
group by u.userID, u.name order by sum(amount*price) desc, u.userID
-- total 사용시
select u.userID, u.name, SUM(amount*price) as total, userclass=
case
when(total >=1500) then 최우수고객
when(total>=1000) then 우수고객
when(total>=1) then 일반고객
else 유령고객
end
from buyTbl b
right join userTbl u on b.userID=u.userID
group by u.userID,u.name order by total desc, u.userID
위 4가지의 경우에 있어,
마지막 total 사용하기만 에러가 발생합니다.
왜 에러가 발생하는 지 알려주시길 바랍니다.
추가적으로 사실 group by에 필요한 열은 u.userID뿐입니댜.
에러가 발생하여 u.Name도 포함을 하게 되었는데,
왜 에러가 발생하는 지에 대한 설명이 책에서는 친절하게 나와있지는 않습니다.
이유를 알려주세요.
감사합니다.