【问题标题】:Get SUM of sales for multiple years in columns在列中获取多年销售额的总和
【发布时间】:2010-11-26 00:11:08
【问题描述】:

我想得到这样的东西:

*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 个查询然后建立一个联合,但也许有更简单的方法?

【问题讨论】:

  • 我们必须猜测您的表结构,这绝不是好事。但是每年一张桌子对我来说似乎是一个概念错误。
  • 这不是一年一张桌子,他只是在做命名。
  • @lijie : 我一定累了,对不起,我的错。
  • 嗯,好像mysql没有pivot——在sql server中,使用pivot关键字轻而易举!
  • Pivot 会很好,是的。很抱歉没有提供表结构,它只是一个基本的订单和客户表。

标签: sql mysql


【解决方案1】:

只需修改其中一个答案即可获得没有订单的客户 -

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

【讨论】:

    【解决方案2】:

    子查询是不可取的,
    但应该可以解决问题

    比如

    SELECT 
      c.name, 
     (
       SELECT 
         ISNULL(SUM(o2009.price), 0)
       FROM orders as o2009
       WHERE 
         o2009.year=2009 AND o2009.customerId=c.id
     ) as sum_2009,
     (
       SELECT 
         IFNULL(SUM(o2010.price), 0)
       FROM orders as o2010
       WHERE 
         o2009.year=2010 AND o2010.customerId=c.id
     ) as sum_2010
     FROM customer c
    

    始终检查查询费用

    【讨论】:

    • 这对于拥有大量客户的数据库的性能而言可能会变得非常丑陋..
    • 感谢您的评论,在我们的例子中我们并不关心,因为我们只是偶尔运行一次。
    • @Remy - 我认为您可以同时发布查询成本进行比较,并始终使用更好和优化的查询。
    【解决方案3】:

    如果你使用select c.name, o.year, sum(o.price) from customer as c inner join orders as o on o.customerId = c.id group by c.id, o.year,你会得到一些有用的东西,但不是你想要的格式。

    【讨论】:

      【解决方案4】:

      试试这个:

      Select c.name, 
         Sum(Case When o2008.year == 2009 Then price Else 0 End) cy2008,
         Sum(Case When o2009.year == 2009 Then price Else 0 End) cy2009,
         Sum(Case When o2010.year == 2009 Then price Else 0 End) cy2010
      From Orders o
      Group By`enter code here` c.Name
      

      【讨论】:

      • 未下订单的客户将不予退货
      • 对客户进行左连接
      猜你喜欢
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多