您需要group by
在外面添加一个子句:
SELECT country as regionname, sum(custamot) as Totsales
FROM (select o.customerid, sum(netamount) custamot, c.country
FROM orders o join
customers c
on o.customerid = c.customerid
group by c.customerid
) iv
group by country;
实际上,您不需要子查询:
select country as regionname, sum(netamount) as Totsales
FROM orders o join
customers c
on o.customerid = c.customerid
group by country;
要在同一查询中获取总数,请使用with rollup
:
select country as regionname, sum(netamount) as Totsales
FROM orders o join
customers c
on o.customerid = c.customerid
group by country with rollup;
最后,要添加年份,要么使用where
子句,要么试试这个:
select year(orderdate) as yr, country as regionname, sum(netamount) as Totsales
FROM orders o join
customers c
on o.customerid = c.customerid
group by year(orderdate), country with rollup;
并将 US 和 ROW 分开:
select year(orderdate) as yr,
(case when country = 'US' then 'US' else 'ROW' end) as region,
sum(netamount) as TotSales
FROM orders o join
customers c
on o.customerid = c.customerid
group by year(orderdate), (case when country = 'US' then 'US' else 'ROW' end) with rollup;