我想得到这样的东西:
*Customer *2009 *2010 *
|------------|---------|--------|
|Peter |120 |240 |
|Johe |455 |550 |
我查询的第一个方法是:
Select c.name, sum(o2009.price), sum(o2010.price) from customer c
join orders o2009 on (o2009.customerId = c.id AND o2009.year = 2009)
join orders o2010 on (o2010.customerId = c.id AND o2010.year = 2010)
group by c.id
不幸的是,这是完全错误的。我想我可以运行2个查询,然后建立一个并集,但是也许有一些更简单的东西吗?
最佳答案
只需修改答案之一即可获得没有订单的客户-
Select c.name,
Sum(Case When o.year == 2008 Then price Else 0 End) cy2008,
Sum(Case When o.year == 2009 Then price Else 0 End) cy2009,
Sum(Case When o.year == 2010 Then price Else 0 End) cy2010
From Customers c left outer join
Orders o on o.customer_id = c.customer_id
Group By c.name
关于sql - 在列中获得多年的销售总额,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4278570/