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

关于SQL分组统计语句
请教如果用sql语句查询下表A得出B表


------解决方案--------------------
SQL code
;with cte as(
select 姓名,类型,sum(衣服*金额)衣服,sum(裤子*金额)裤子,sum(鞋子*金额)鞋子,sum((isnull(衣服,0)+isnull(裤子,0)+isnull(鞋子,0))*金额)总金额
from tb group by 姓名,类型
)select * from cte
union all
select 类型+'总计金额',类型,sum(衣服),sum(裤子),sum(鞋子),sum(总金额) from cte group by 类型 order by 类型,姓名

------解决方案--------------------
SQL code
--刚才只替换了一部分
select * from 
(
select 姓名,类型,
sum(衣服*金额)衣服,sum(裤子*金额)裤子,sum(鞋子*金额)鞋子,sum((isnull(衣服,0)+isnull(裤子,0)+isnull(鞋子,0))*金额)总金额
from tb group by 姓名,类型
) aa
union all
select 类型+'总计金额',类型,sum(衣服),sum(裤子),sum(鞋子),sum(总金额) from 
(
select 姓名,类型,
sum(衣服*金额)衣服,sum(裤子*金额)裤子,sum(鞋子*金额)鞋子,sum((isnull(衣服,0)+isnull(裤子,0)+isnull(鞋子,0))*金额)总金额
from tb group by 姓名,类型
)bb
group by 类型 order by 类型,姓名