|
我的数据库中有一些数据:
9 l/ n1 }! w, i9 J# p# o0 r' F0 Iid user
: c+ N+ d3 k4 X% y( H1 zhangsan
0 v _5 j. Q, Q, @/ j2 zhangsan / q6 U5 |& }6 O% o. e8 ?
3 zhangsan
- p) o0 U" f+ I; A; w' Q2 Q% o4 lisi
& [# y/ F( ^, W7 i1 ~8 o/ d- k5 lisi
7 Z9 A2 m9 w; ~) }. A* }3 F, \6 lisi . @8 d6 }) _9 B7 t L
7 zhangsan 7 i% z) M( W# B* D* L
8 zhangsan
" d# |. R7 T- w+ O' @我要保持秩序,并合并几乎相同的用户物品,该怎么办?当我使用shell脚本时,我将(文件测试中的数据。):
: a& r( x# D+ I: [' mcat test|cut -d " " -f2|uniq -c
- n( e. s; ?/ V( I# P! W这将得到结果为:7 t5 `# _5 T ~! Y
3 zhangsan
* Z1 f" s h& Q$ a- T# W 3 lisi
+ D! q; d# F- d4 S 2 zhangsan
7 z# z' N3 v- D& k; t; l但是如何使用sql呢?9 }3 j) i1 D' j; F0 u I
! L( a) q, i" r
解决方案:( r6 u! Q! C8 }
. s1 |2 u- c3 a4 |8 @
6 b$ d/ h6 _% F3 n( z& L
2 H$ G6 H7 W5 Y: K
如果你试试:
" J( B! \+ M: Q/ D9 mSET @name:='',@num:=0;( V. t$ F, j- |& n2 T0 W$ ] W b7 Y
SELECT id,/ J7 X* R: G3 _3 Z3 |
@num:= if(@name = user, @num, @num + 1) as number,. x% C/ `& f; Q/ z! l
@name := user as user
6 B3 K0 f4 h: n% T% ?FROM foo
# L& j t8 W7 T2 cORDER BY id ASC;
+ K' l- e1 ?; {6 y* z# Z) x这给出了:
; \, u! A# \' O1 N' H! k" w, v% H! t' a+------+--------+------+! w0 P2 `+ a' M0 K; ~+ W/ ~# E
| id | number | user |
5 A( z# X. a3 b4 ~+------+--------+------+: z7 E1 n4 J( }: |3 w/ G; y
| 1 | 1 | a |# J3 r; f9 F* n( ]9 B. p' m* X
| 2 | 1 | a |: ^2 @3 H( H: w( t; A
| 3 | 1 | a |
4 S2 c, {$ C# Z| 4 | 2 | b |9 B8 v8 ] J( F. R
| 5 | 2 | b |$ X/ J) Y& O4 g* ^6 w$ ^! c
| 6 | 2 | b |$ O* ~- U/ G2 G4 N
| 7 | 3 | a |& a& w- e8 S) k( r% B
| 8 | 3 | a |, k' w& U3 ^* j/ t
+------+--------+------+
* B4 A$ ], g2 P因此,您可以尝试:
; z# { q; p# K. ^SET @name:='',@num:=0;
8 G* B) ]- c' I, Z9 r3 T CSELECT COUNT(*) as count, user
; o5 q+ E7 ]; q( ^4 ^5 h( a; Z. G9 OFROM (( H+ z& M: j; Q7 P/ L
SELECT @num:= if(@name = user, @num, @num + 1) as number,( ?7 t- @# x9 a: s$ V) ?
@name := user as user0 m& M5 I. u$ j0 ^; W( l* r; Y
FROM foo
8 P( n% ?- ?1 T, Z" dORDER BY id ASC
% r: C( z! s$ k' ^: K+ K, f2 ~3 {/ f6 A) x
4 ^ x; j+ k& B4 fGROUP BY number;" \+ V) i$ k: O3 |
这使, J. k$ {; K$ y
+-------+------+
6 ]" U( ], M8 ?| count | user |
. D- m! B4 U' i5 m7 q+-------+------+( {/ B; v, C: U- L6 o; \1 l% g
| 3 | a |
& C) r9 @& { o0 H5 f+ P, P| 3 | b |
# Z- n3 Z8 G' O0 Y+ ]( m6 h9 |& K" T| 2 | a |
7 X3 p$ u' U3 Z/ d4 h+-------+------+
4 V+ q5 S* f \2 O( @# v! C0 H X7 ~( G(我打电话给我的表foo,也只是使用的名称a和b因为我懒得写zhangsan,并lisi一遍又一遍)。 |
|