0

我尝试进行查询,我可以在数据库中看到 2007 年和 2008 年美国和世界其他地区的销售净额以及所有小计和总计。(值得一提的是,美国和 World 是区域,已在数据库中编码)

我的查询:

SELECT country regionname, sum(custamot)Totsales 
FROM( select o.customerid, sum(netamount) custamot, c.country
FROM orders o join customers c
on o.customerid = c.customerid
where country like 'US' 
group by c.customerid ) iv;

这个查询只是告诉我美国的总销售额(你可以看到没有一年)。我尝试了没有该部分的查询:

where country like 'US' 

但结果是一样的。我找不到向我显示特定年份的美国和世界的查询...

任何想法都会有所帮助

谢天谢地,乔普

4

3 回答 3

0

您需要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;
于 2013-04-02T02:19:35.413 回答
0

像这样的东西:

SELECT country as regionname, sum(custamot)Totsales 
FROM( select o.customerid, sum(netamount) custamot, c.country
      FROM orders o join customers c
       on o.customerid = c.customerid
      where left(my_date,4) between 2007 and 2008
      group by c.customerid ) iv
group by country

萨卢多斯 ;)

于 2013-04-02T02:23:22.803 回答
0

要获得某一年的结果,假设您有一个日期字段,

where YourDateField >= {d '2007-01-01'}
and YourDateField < {d '2008-01-01'}
于 2013-04-02T02:24:03.070 回答