|
我有一张表,上面有像" M& B2 k7 [( G) S
id keywords* G0 D, f: v8 F9 k+ p
1 cat, dog, man, mouse
* D7 e/ u, D- g2 man, pen, pencil, eraser' X0 m! k8 U* y
3 dog, man, friends" d, W+ Q' f- D& F& N' H3 ]# ]
4 dog, leash,......# ?+ ?4 U6 M9 ]1 \7 x6 l
我想做一张像这样的桌子6 {5 W4 p6 a; E0 A6 v1 A
id cat dog man mouse pen pencil eraser friends leash ......) g0 k/ [: U+ ~& b; M
1 1 1 1 1 0 0 0 0 04 L7 O/ D! v1 G
2 0 0 1 0 1 1 1 0 0; N8 O/ H& [1 V, R( I4 G# ~
3 0 1 1 0 0 0 0 1 0
) |* ^1 U0 W9 l* X1 Y9 m$ h- ]等等。2 Y9 w0 r- {3 q( G ]( c
& _. i( T0 N, Q. ], K1 f解决方案:
9 t$ o) K. W* r$ ^* ^1 j/ r+ C
+ b0 i% U, L1 t r0 y
) @* K4 N4 [5 `6 Q6 ]
' i! {0 j8 N7 S WITH basedata(id,keywords) AS
* e+ U& X4 i2 q3 g" b (6 ]! O: e5 |) b7 p8 i
SELECT 1,’cat, dog, man, mouse’ union all
6 a" {! N9 ~ ]) z2 j0 C SELECT 2 ,’man, pen, pencil, eraser’ union all
6 m& S j+ d+ Y x SELECT 3,’dog, man, friends’ union all5 N$ _$ }. |8 Y5 ^& i
SELECT 4,’dog, leash’ o+ S, Z4 y$ Q1 a2 T2 j; y
),
. x5 y; n- I* U: @% I" |; P cte(id, t, x)
* r, G. ?6 j: v0 ^, ~& H) a y AS (SELECT *,
6 o' X, g, J& q `( L# T CAST(‘‘ + REPLACE(keywords,’,’,’‘) + ‘‘ AS XML)
+ X% @$ L; J0 w2 \* k( t FROM basedata)
; F9 ^% P) E2 Y3 A SELECT id,6 ^4 s$ } i3 P* j9 W4 D- D+ t# B
LTRIM(RTRIM(w.value(‘.’, ‘nvarchar(max)’))) as keyword
$ L) o7 }. Q6 w3 E6 H) d INTO #Split
8 Y% G" `. `5 ~5 j$ D FROM cte- G& g6 R. [. D/ x* ]/ N
CROSS APPLY x.nodes(‘//foo’) as word(w) " m+ x) r! v: | P! U% l
DECLARE @ColList nvarchar(max)
* A& V Y# C3 [* w! H* {SELECT @ColList = ISNULL(@ColList + ',','') + keyword
1 O2 H5 U7 I; T+ L3 ^' |; SFROM (0 k2 S# _2 z9 H- l1 i5 ~6 h
SELECT DISTINCT QUOTENAME(keyword) AS keyword
, q C+ L. m Q5 z- k5 g1 z" b3 \FROM #Split7 r# L, z! t e8 @" m
) T' Y$ w6 y I0 i
EXEC(N'
2 p( d3 F' A3 I9 n, |0 S* w+ h6 iSELECT *& S8 P1 X$ m2 Q' P
FROM #Split% H g: Q+ \/ B. I6 e
PIVOT (COUNT(keyword) FOR keyword IN (' + @ColList + N')) P'); O: u& }" c- T/ @3 @# W) h& Y
DROP TABLE #Split N" l5 M3 `5 }9 J* p5 r4 o( H
给- c% O: `/ ?& m" [- P! p6 Y
id cat dog eraser friends leash man mouse pen pencil
# O+ q% w9 U) B7 I* ?----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
; o: d& M; H/ [: e- o1 1 1 0 0 0 1 1 0 0: l8 V- B( w' o" R- S/ p; ]
2 0 0 1 0 0 1 0 1 1( Y! Y& K" | j/ c8 g/ M" q
3 0 1 0 1 0 1 0 0 0. i# @0 B2 B6 F4 t' B
4 0 1 0 0 1 0 0 0 0 |
|