我现在的数据库结构是这样的
table
A B C D E F
1 1 1 3 4 5
1 1 2 2 4 5
1 1 3 3 4 5
1 2 1 3 3 5
1 2 2 3 4 5
1 2 3 3 1 5
2 3 1 1 2 3
2 3 2 3 4 5
2 3 3 6 7 8
========================================
我要把以C列转成横向的
A B 1 2 3
每一栏数据这个pivot怎么样写啊要转不对
select [1],[2],[3] from
(select * from table) as p
Pivot
(聚合涵数 for c in ([1],[2],[3])
===================================
这个聚合涵数怎么写啊,本来我想在最后按C分组的这个思路也不对
table
A B C D E F
1 1 1 3 4 5
1 1 2 2 4 5
1 1 3 3 4 5
1 2 1 3 3 5
1 2 2 3 4 5
1 2 3 3 1 5
2 3 1 1 2 3
2 3 2 3 4 5
2 3 3 6 7 8
========================================
我要把以C列转成横向的
A B 1 2 3
每一栏数据这个pivot怎么样写啊要转不对
select [1],[2],[3] from
(select * from table) as p
Pivot
(聚合涵数 for c in ([1],[2],[3])
===================================
这个聚合涵数怎么写啊,本来我想在最后按C分组的这个思路也不对
max(case c then 1 then c else 0 end) [1],
max(case c then 2 then c else 0 end) [2],
max(case c then 3 then c else 0 end) [3]
from tb
group by a,b
max(case c when 1 then c else 0 end) [1],
max(case c when 2 then c else 0 end) [2],
max(case c when 3 then c else 0 end) [3]
from tb
group by a,b
59 265 1 7 5 6
59 265 2 5 1 359 266 1 1 2 1
59 266 2 3 7 960 267 1 4 5 6
60 267 2 7 8 9
==========================
现在要变成A B E F G H J K
59 265 7 5 5 1 6 3
59 266 1 3 2 7 1 9
59 267 4 7 5 8 6 9
.............................以C的次序把其它几列转成行
max(case c when 1 then D else 0 end) 'E',
max(case c when 2 then D else 0 end) 'F',
max(case c when 1 then E else 0 end) 'G',
max(case c when 2 then E else 0 end) 'H',
max(case c when 1 then F else 0 end) 'J',
max(case c when 2 then F else 0 end) 'K'
from tb
group by A,B
insert into tb values(59, 265, 1, 7, 5, 6)
insert into tb values(59, 265, 2, 5, 1, 3)
insert into tb values(59, 266, 1, 1, 2, 1)
insert into tb values(59, 266, 2, 3, 7, 9)
insert into tb values(60, 267, 1, 4, 5, 6)
insert into tb values(60, 267, 2, 7, 8, 9)
goselect A,B,
max(case c when 1 then D else 0 end) 'E',
max(case c when 2 then D else 0 end) 'F',
max(case c when 1 then E else 0 end) 'G',
max(case c when 2 then E else 0 end) 'H',
max(case c when 1 then F else 0 end) 'J',
max(case c when 2 then F else 0 end) 'K'
from tb
group by A,B
drop table tb/*
A B E F G H J K
----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
59 265 7 5 5 1 6 3
59 266 1 3 2 7 1 9
60 267 4 7 5 8 6 9(3 行受影响)
*/
你现在这样写,他行是固定的
要是我有1W条,或1W条以上呢
那我MAX不要写疯拉。
那max语句,我不是要写N多啊
用pivot也解决不了问题,只是可把其它一组使用聚合函数
给个例子参照:
http://blog.csdn.net/roy_88/archive/2007/02/13/1509413.aspx