I have been dealing with a join problems for a while now and I think I need some help. I'm studying northwind database to practice a little bit and I'm struggling joining two derived tables. the error I get is 'northwind.allorders table does not exist' and that is code;
select cgroups.customergroup,count(*) as totalingroup, (cgroups.customergroup/totalingroup) as percentage
from
(select customerid,companyname,totalamount,
case when totalamount between 0 and 1000 then 'low'
when totalamount between 1000 and 5000 then 'medium'
when totalamount between 5000 and 10000 then 'high'
when totalamount >= 10000 then 'very high' end as customergroup
from allorders
order by customerid) as cgroups
join(select c.customerid,c.companyname, sum(od.quantity*od.unitprice) as totalamount
from customers as c
join orders as o
on o.customerid=c.customerid
join `order details` as od on od.orderid=o.orderid
where cast(o.orderdate as date)>= '19960101' and cast(o.orderdate as date)<'19970101'
group by customerid) as allorders on allorders.customerid=cgroups.customerid
group by customergroup
order by totalingroup desc;
what I wanna do basically is to group customers by their spending on 1996 as low,medium,high and very high and then see how many customers there are in each group and the percentages of these groups. But the mysql gives ''northwind.allorders table does not exist'' error when I execute the above code. Can anyone please tell me where I mistake? Thank you for your time.
I think you are trying for something like this:
select (case when ct.totalamount < 1000 then 'low'
when ct.totalamount < 5000 then 'medium'
when ct.totalamount < 10000 then 'high'
else 'very high'
end) as customergroup,
count(*),
count(*) / sum(count(*)) over () as ratio
from (select c.customerid, c.companyname,
sum(od.quantity * od.unitprice) as totalamount
from customers c join
orders o
on o.customerid = c.customerid join
`order details` od
on od.orderid = o.orderid
where o.orderdate >= '1996-01-01' and o.orderdate < '1997-01-01'
group by c.customerid, c.companyname
) ct
group by ct.customergroup
order by count(*) desc;
Your query is a bit of a mess. I would recommend that when writing queries that you start by formatting the code so one can follow it.
Then:
GROUP BY
keys and SELECT
keys match.orderdate
to a date
for a comparison.case
expressions, the conditions are matched in order . That means that between
is unnecessary -- and cumbersome if you want to change the bounds.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.