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

求一条简单的语句!!
table1表(字段a1,字段a2,字段a3)
求一条语句,得到下面的结果集:
N SUM
---------------
N1 sum(a1)
N2 sum(a2)
N3 sum(a3)

//N1,N2,N3为任意标识

即得到上面三条数据,求解!

------解决方案--------------------
SQL code
select 'N1' as Col,sum(a1) from table1
union all
select 'N2' as Col,sum(a2) from table1
union all
select 'N3' as Col,sum(a3) from table1

------解决方案--------------------
select 'N1',sum(a1) union all
select 'N2',sum(a2) union all
select 'N3',sum(a3)
------解决方案--------------------
SQL code
select 'N1' as N,sum(a1) AS [SUM] from table1
union all
select 'N2' as N,sum(a2) from table1
union all
select 'N3' as N,sum(a3) from table1


--or

SELECT *
FROM (SELECT SUM(a1) AS N1,SUM(a2) AS N2,SUM(a3) AS N3) AS a
PIVOT 
([Sum] FOR N IN(N1,N2,N3)) AS b

------解决方案--------------------
探讨

楼上的,哪个最好呀?

------解决方案--------------------
探讨
楼上的,哪个最好呀?

------解决方案--------------------
探讨

引用:
楼上的,哪个最好呀?

CTRL+L查看查询计划。

------解决方案--------------------
SQL code

select N='N1',[sum]=sum(a1) from table1
union all
select 'N2',sum(a2) from table1
union all
select 'N3',sum(a3) from table1