|
我写了这个查询:
3 G+ o* @8 O! x5 s ~SELECT s, [1] AS a1, [2] AS a2, [3] AS a3, [4] AS a4
! e, w' L: l0 T( L, l RFROM (SELECT grade, aid, s FROM m) p# s5 J3 t1 e' _! B3 L" \
PIVOT
; Y2 {; J5 M* c2 k- G* N() L; l m- V" N% }; u) @
SUM(grade)& @( ?3 X- U5 O4 W8 |) W
FOR aid IN ([1], [2], [3], [4])
' F0 f4 N, P( n5 D$ h) AS pvt ORDER BY pvt.s;
6 r; h1 i J0 R/ n# v7 G( W0 T- E4 v返回结果:; k% H e* [" @0 Y
s a1 a2 a3 a4
& j' ^3 S, B+ y: d) A, f3 L1 o1 25 69 95 565 }0 M5 c/ _: U5 c
2 27 99 16 876 p+ ?* R1 O2 p. S9 v
. . . .
, v5 R& `$ E0 N+ E# ]3 g3 r4 B+ c# U99 98 12 34 76
/ i9 w, Z- U. C: z: _7 U这正是我想要的结果。我的问题是,“援助”中不会总是有四个不同的值。是否可以重写此查询(或使用存储过程),以使“ a2 T5 v n* F0 {7 `2 S1 Z" _% c
*”列的数量取决于“援助”中有多少个不同的值?' l2 m5 _- _2 r
# U9 Y7 ~; ?6 A& V
解决方案:! V! z' {( } I
$ n% j/ q4 h( V# B( R$ ^4 J& y$ C1 o
8 D' K7 G+ N" q: s. W/ M
m5 b; S" J6 L8 |
您将需要使用“动态数据透视表”来获取所需的列列表。这将首先检索列的列表,然后旋转该列表。类似于以下内容:8 A- Q! S. v; w( b0 j
DECLARE @cols AS NVARCHAR(MAX),& h2 _7 S2 u9 a
@query AS NVARCHAR(MAX);
) [2 L M# D! q2 qselect @cols = STUFF((SELECT distinct ',' + QUOTENAME(aid) # V$ T4 t/ D% n8 @2 u- l
FROM m
; P% N2 L6 I8 B p1 d7 q; r% L- t$ ^ FOR XML PATH(''), TYPE
+ E+ ]) x4 f' p# P ).value('.', 'NVARCHAR(MAX)')
, t8 d0 m; K/ m ,1,1,'')
2 f, _3 x; m' E4 I! T8 v- Eset @query = 'SELECT s, ' + @cols + ' from 5 s+ Y* _+ Q$ b' ]# G A
(
4 W0 [8 B0 {/ `+ s p( G2 i& W select grade, aid, s8 l* \! H) K! z, T( B# i
from m
" y; o* v6 h6 j2 Y( o4 p8 K8 L ) x
! W& b0 O% M3 C$ d2 S pivot ' q* ]4 n) W" y* t: X. n- ~
( x e K6 I5 M1 K
sum(grade). |1 Q, F' z- f; V4 Y; W
for aid in (' + @cols + '), A' C! I+ \8 x# D D3 U
) p * n& H' R" Q9 J0 {* g/ W
ORDER BY p.s'
' Q' g g ]2 _9 P% N* L" R/ G wexecute(@query) |
|