日期:2014-05-18  浏览次数:20503 次

100分--组合查询问题--在线等!!!!!
表: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年的订单总额。

多谢指教!

------解决方案--------------------

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
------解决方案--------------------
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
------解决方案--------------------
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