|
我正在使用两个表在SQL Server(SSMS)中工作:) z5 Z8 t8 S) F# w8 o, b) y
prop_ppl:+ R3 |- A" j3 D: r
id_numb id_pers cdate val9 J4 `8 d+ g# x+ H
1 4 NULL NULL
& H; g5 n/ W% {, l2 2 2018-12-12 250
) c4 h5 @- _ u$ `7 q2 T3 1 2018-12-01 250" R0 q+ e5 L4 @- T1 ?+ k( Y b
4 3 2018-12-11 500, a% k6 ]. W( Y, T
5 6 2018-01-01 500 g1 p y w; Z5 D3 g# |
6 5 2018-12-12 480" d7 z& c1 f* `5 R
ppl:" P$ G2 V% H$ d" z8 G3 V" I
id_perc name' f& P/ N% i. i% }
1 John
0 J1 }( p: Q% M) D2 Derek
1 h8 i% U8 g. `8 |, g- [3 Mia% a' @# ?# i. z2 j( E; }0 Y. c
4 Chris
7 @, z/ Z. f2 v: @9 x s* f6 A% Z5 Ann
2 i v/ s F# T3 M+ F8 @$ d6 Dave
& I8 Z% o8 S0 t k( U然后我需要得到这样的表:& P* H. d. Y9 b7 {* F" g- e4 T
name0 `. F+ M# T0 x2 M
id_numb value3 b5 W0 E/ U0 {4 h Q+ M
对于这些表,应在必要时查找日期为2018/12/12的ppl的所有值:
. ^9 r3 a6 D8 c( S+ e, G7 K4 i, g Derek Ann* w5 }$ y0 \1 J# \0 f
2 250 0
$ o: f/ ]! w8 I; u5 J# Z' V6 0 NULL
: C$ s4 F% ?( \8 U4 F# Y9 P代码:
6 v+ w7 f5 t+ Y) E) B1 {CREATE TABLE ppl(3 f0 v2 V4 N* q9 J" P
id_perc smallint PRIMARY KEY,4 _0 P! P" p4 I2 M7 P( W" E' Z
name varchar(50) NOT NULL
7 \, i' r$ `; @% l" J). k( ?! e; i0 z& D9 u+ V2 @ V
CREATE TABLE prop_ppl(* h* \* @5 `& [* K) b/ f6 s
id_numb int IDENTITY(1,1) PRIMARY KEY,
* O% n2 I2 `3 T/ D2 S8 l* m id_perc smallint NOT NULL,
* N1 y. Q2 k( s; k0 }4 n, q2 ]7 | cdate smalldatetime,
4 U4 d; w* G( h' e val int
& u* m0 a: n! _/ | )
$ @ p4 j6 U) m0 aINSERT INTO dbo.ppl (id_perc, name): k9 T$ @' g. N h. Y' \# @
VALUES (1, 'John'), (2, 'Derek'), (3, 'Mia'), (4, 'Chris'), (5, 'Ann'), 8 q! |: y" j* u: T* z" c
(6, 'Dave') U0 O3 K' X5 t! Y m+ Z
INSERT INTO dbo.prop_ppl (id_perc, cdate, val)
4 s1 S) m# j: Z3 I1 g$ r7 bVALUES (4, NULL,NULL), (2,'20181212', 250), (1, '20181201', 250),
1 b m7 K0 `+ Y; e2 x (3, '20181211',500), (6,'20180101', 500), (5, '20181212', 480)/ q* K# S: o6 G3 u3 l2 t
然后我尝试使用:
2 b( B/ t' n1 G4 d" M |1 q) i; ySELECT *
/ s6 v- k" X, sFROM ( # o' z! ~: l a: Q0 G
SELECT name,id_numb,val 0 M8 S( X8 X* m/ I& v" m/ s, ^8 a3 i
FROM prop_ppl ' @4 Q( t- c' n% `% c$ h k
JOIN ppl ON prop_ppl.id_perc = ppl.id_perc
- M1 T$ ]) o" @; X WHERE cdate='20181212'. |: k0 k4 m# }
)
9 F S: Q7 [) C* \PIVOT(
; G6 _! e. d( y SUM(val) 8 b2 {0 w1 v% ]3 e3 C
FOR [name] in ('Derek','Ann')
3 u* Y( n: M8 }7 [2 q )8 C% {- [% z( l- A$ n
但出现错误“ 关键字“ PIVOT”附近的语法不正确。 ”' X0 V+ s. `/ K; Y3 o4 d5 [
也许,也可以不使用PIVOT。。另外,我想了解如何将此脚本应用于任意参数(而不仅仅是Derek和Ann)。: z4 u2 a, d$ h1 j4 x: s1 w
6 E) U1 \$ B; `" ]0 j( U
解决方案: |
|