表:account
字段:accountid,accountname,accounttype
表:salesorder
字段:accountid,salesorderid,orderdate,ordertotal表account与表salesorder是一对多关系,一个客户有多个订单问题:想通过一个sql语句得到
accounttype,accountname,ordertotal(2004年),ordertotal(2005年),ordertotal(2006年)
按照accounttype(客户类型)分组,安装accountname(客户名称)汇总04,05,06年的订单总额。多谢指教!

解决方案 »

  1.   


    select 
    accounttype,
    accountname,
    case when year(orderdate)=2004 then ordertotal else 0 end as [ordertotal(2004年)],
    case when year(orderdate)=2005 then ordertotal else 0 end as [ordertotal(2005年)],
    case when year(orderdate)=2006 then ordertotal else 0 end as [ordertotal(2006年)]
    from account a
    inner join salesorder b on a.accountid=b.accountid
    group by accounttype,accountname
      

  2.   

    select
        a.accounttype,
        a.accountname,
        sum(case year(s.orderdate) when 2004 then s.ordertotal else 0 end) as [ordertotal(2004年)],
        sum(case year(s.orderdate) when 2005 then s.ordertotal else 0 end) as [ordertotal(2005年)],
        sum(case year(s.orderdate) when 2006 then s.ordertotal else 0 end) as [ordertotal(2006年)]
    from
        account a
    left join
        salesorder s
    on
        a.accountid=s.accountid
    group by 
        accounttype,accountname
      

  3.   

    select a.accounttype,a.accountname,
      sum(case when year(b.orderdate)=2004 then b.ordertotal else 0 end ) as 2004年,
      sum(case when year(b.orderdate)=2005 then b.ordertotal else 0 end ) as 2005年,
      sum(case when year(b.orderdate)=2006 then b.ordertotal else 0 end ) as 2006年
    from account a
      left outer join saleorder b on a.accountid=b.accountid
    group by a.accounttype,a.accountname
      

  4.   

    --如果数字开头作为字段名或别名,必须加[]。select 
    accounttype,
    accountname,
    case when year(orderdate)=2004 then ordertotal else 0 end as [ordertotal(2004年)],
    case when year(orderdate)=2005 then ordertotal else 0 end as [ordertotal(2005年)],
    case when year(orderdate)=2006 then ordertotal else 0 end as [ordertotal(2006年)]
    from account a
    left join salesorder b on a.accountid=b.accountid
    group by accounttype,accountname
      

  5.   

    谢谢各位,我试了试可以查出订单列表,但是分类的效果没有出来,类西下面的效果:
    type1
         客户1  04订单,05订单,06订单
         客户2  04订单,05订单,06订单
    type2
         客户1  04订单,05订单,06订单
         客户2  04订单,05订单,06订单如何实现啊??????
      

  6.   

    select
        a.accounttype,
        a.accountname,
        sum(case year(s.orderdate) when 2004 then s.ordertotal else 0 end) as [ordertotal(2004年)],
        sum(case year(s.orderdate) when 2005 then s.ordertotal else 0 end) as [ordertotal(2005年)],
        sum(case year(s.orderdate) when 2006 then s.ordertotal else 0 end) as [ordertotal(2006年)]
    from
        account a
    left join
        salesorder s
    on
        a.accountid=s.accountid
    group by 
        a.accounttype,a.accountname
    order by 
        a.accounttype,a.accountname