|
我有一个SQL Server 2008表,我需要从中选择一个运行余额
! q$ d1 q7 N4 h" w2 u& x* W1 F. g1 }TransDate Credit Debit Datasource
" e' p# W0 j3 b! {6 t, c------------------------------------------
E6 T; K. p+ C+ c* x2014-01-01 5000 NULL 3
! s4 `0 l' T9 Y* B2014-01-07 NULL 2000 3
4 r$ F3 d/ M w1 M- p2014-01-11 5000 NULL 3: M) E D6 G; O0 Z S' y1 u& F# ^
2014-02-03 6000 NULL 4
0 i" x6 |. }+ z; d2 ?5 }2014-02-06 NULL 4000 4* }" A" p9 l8 {0 Q* |2 I1 I; b0 F
2014-02-11 3000 NULL 4
: J. Y/ E: f5 [2014-02-21 NULL 1000 3
D4 k) Q6 q# H0 ?2014-02-28 2000 NULL 32 n: ^. u6 d1 N o3 @
2014-03-01 5000 NULL 3
) h3 N# C% `& v2 B: J, u我尝试了相关查询/ p z" p& ~+ ^- y
Select " h& M! J: z$ L) [+ r+ q
t.TransDate, / [/ t- k( ^ @4 b0 z
t.Credit, & u$ ^8 A1 \8 w$ Z
t.Debit, * J* S6 D# X5 K( b4 T
(Select sum(coalesce(x.credit, 0) - coalesce(x.debit, 0))
5 d4 g2 M9 ~: h" e$ O0 Z From Transactions x & ^% Q7 u2 X5 }
WHERE x.DataSource IN (3,4) AND (x.TransDate >= '2014/02/01' AND x.TransDate 但是我得到了所有的空值Balance。3 v7 b' R5 C5 m! i1 ?
预期输出为. f, C; x. @' D4 C# m0 A$ C" }
TransDate Credit Debit Balance
; ^: K2 ~" ]5 V& S5 `; a5 Z9 \------------------------------------------
2 p7 T; x3 c, T: D4 K* ~# W2014-01-11 NULL NULL 8000 您需要自加入表。' {9 O q; b4 e1 @0 c6 H
CREATE TABLE Test1 i) b8 h% ]5 O1 B9 i
(* A, G0 `+ b6 i3 P, Q
TransDate DATE,$ t) c3 R g" J9 Z- O2 W% L |
Credit INT,
/ A0 ~: y3 t* ^* b. c4 @ Debit INT,1 {% I5 `6 F n; f. u
);: x, p& r$ t4 x* P* ?9 T: d0 p+ d
INSERT INTO Test VALUES: K/ h8 q% |% }0 Z: B" f
('2014-01-01', 5000, NULL), p' j& X8 a3 V1 t; ]4 ]
('2014-01-07', NULL, 2000), 5 a, w# i2 z4 z0 W
('2014-01-11', 5000, NULL), 7 C. }) O! u4 A) c& p
('2014-02-03', 6000, NULL),
% U( G @3 d, ~('2014-02-06', NULL, 4000), 9 f: O# d- \0 O1 z( g& g8 X% C- \
('2014-02-11', 3000, NULL), & w+ N: [! D/ R5 C) j
('2014-02-21', NULL, 1000),
0 H+ Y9 I& X; t('2014-02-28', 2000, NULL),
& q. p9 [; b- V W$ p' ^: m* y$ c('2014-03-01', 5000, NULL)( I8 o0 I/ H/ N4 [- A6 l
WITH CTE AS
. U! Q' W. ]7 b(
7 p$ }2 b. P4 j% M$ p. [, E3 VSELECT t2.TransDate, & D9 s) F3 {# Y: Z' m8 l4 G; V
t2.Credit, 1 v; N. S, h) x3 b$ `) d; q& }8 f2 [
t2.Debit, 2 I( o3 ~2 }8 b9 ]& o& I
SUM(COALESCE(t1.credit, 0) - COALESCE(t1.debit, 0)) AS Balance
L9 F& `7 S; z( d! u; g- X- ^FROM Test t1 7 o# Q# v4 b P* d7 K
INNER JOIN Test t2' I4 s9 d8 R. `/ w$ G2 T" @
ON t1.TransDate = '2014/01/11' AND TransDate 输出& T" X) F) l& U" U- P# {8 \
TransDate Credit Debit Balance
2 e7 _) U2 R# O( L3 b3 h R) L8 B2014-01-11 5000 (null) 8000
" M4 Q2 G; T( B4 [8 y- v" f2014-02-03 6000 (null) 14000
' h$ t( D8 V* H; g$ [2014-02-06 (null) 4000 10000( T% a% c& E% {) b* T
2014-02-11 3000 (null) 130002 ?- t x Z% g1 @
2014-02-21 (null) 1000 12000
5 Q; m- [# \$ E1 L8 \6 Y! h" x2014-02-28 2000 (null) 14000
: B. w {5 X$ MSQL字段 |
|