几个SQL问题
一、表结构如下:
table1:
type amount
A 90
B 80
C 70
要求查询结果:
A B C
90 80 70
如果想用MS-SQL做,怎么实现?
二、表结构如下:
table2:
mark tyear amount
A 2006 500
B 2006 300
B 2007 150
C 2007 200
C 2006 350
A 2007 260
结果1:
mark 2006 2007
A 500 260
B 300 150
C 350 200
结果2:
mark amount
A 760
B 450
C 550
要求用一条SQL语句查出结果,这是针对MS-SQL的,如果还有ORACLE的答案,可以也写出来,大家学习讨论一下~
------解决方案----------------------2.
--结果1
--如果tyear固定
Select
mark,
SUM(Case tyear When 2006 Then amount Else 0 End) As [2006],
SUM(Case tyear When 2007 Then amount Else 0 End) As [2007]
From
table2
Group By
mark
--如果tyear不固定
Declare @S Varchar(8000)
Select @S = 'Select mark '
Select @S = @S + ', SUM(Case tyear When ' + Rtrim(tyear) + ' Then amount Else 0 End) As [ ' + Rtrim(tyear) + '] '
From table2 Group By tyear
Select @S = @S + &