|
我有下表
# G# c! z" O; X# WCREATE TABLE Test" K9 \! r3 x9 {+ \. U! s! ]. d! Y Q
(`Id` int, `value` varchar(20), `adate` varchar(20))
* f! C* H& W: P9 x% ];/ @: S6 \* x6 D: ]
INSERT INTO Test
7 [* X: {+ v0 z* c (`Id`, `value`, `adate`)0 p ]8 |$ D3 L" u+ j* U1 b: q
VALUES/ V9 g9 I! ?0 d. d! M& L
(1, 100, '2014-01-01'),
- d7 x1 v' \, g6 P: _ (1, 200, '2014-01-02'),$ ` ^% `8 x5 S, _$ U# K9 C
(1, 300, '2014-01-03'),
0 d/ X8 A3 V7 f5 Z- ? v1 u% t (2, 200, '2014-01-01'),
, o) A/ Z4 z. ~5 Q) H/ n) H (2, 400, '2014-01-02'),( Z* @9 k; r- B, u
(2, 30 , '2014-01-04'),
' O9 t7 V* x- [8 ` (3, 800, '2014-01-01'),+ P# p0 L' F0 n* g! i. \
(3, 300, '2014-01-02'),
3 R* Q7 A8 v9 r6 p# N% U- A9 q7 _# o (3, 60 , '2014-01-04')
- C4 s$ X+ E Y) W6 u;: U- i; @4 n- v2 P/ x
我想实现只选择具有日期最大值的ID的结果。IE
1 d' z' c: o8 o. Oid,value,adate
5 v7 r! \" E n+ i& S. W4 p- N$ X 1, 300,'2014-01-03'
' d1 R) G3 w% }* T1 o 2, 30 ,'2014-01-04'
- s- |' ]" z7 X' A5 u 3, 60 ,'2014-01-04'
0 }8 L# i8 u4 @ I% |- Y' L我该如何使用group by呢?我做了如下,但它不起作用。
! H) H" b" i$ J3 r7 k# c) tSelect Id,value,adate
/ K8 W* I: e7 Z3 nfrom Test
! K# U) r, J s% d& Lgroup by Id,value,adate
5 b) A6 q* E: t l5 P* o6 }7 t" M( Z1 [having adate = MAX(adate)
# f5 A7 D/ [+ \$ l1 D, U+ c: P5 a, x有人可以协助查询吗?( |7 q& f$ I. z6 r: r1 l% }3 o
$ x0 e6 [/ Y; K1 @$ Z0 r" g解决方案:
2 q/ r5 v* ^$ a$ o* u ' L# H; |- H: B5 u& e3 p& P- U$ v
1 }1 T7 e$ k8 c2 g8 F2 s8 s$ x% R b7 ?7 R' k- S; f7 f6 P
如果您使用的是具有分析功能的DBMS,则可以使用ROW_NUMBER:. `6 T9 G1 i" B# A) k+ l; E
SELECT Id, Value, ADate
! I; u2 q* p+ f7 rFROM ( SELECT ID,& j5 k# P/ P& D% c+ Z5 o
Value,
: j/ K+ ^4 a, n% q0 ^ ADate,% F4 H) R. J+ @: d% S2 [! q. ~
ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Adate DESC) AS RowNum
( Y, ]0 y( c4 y! X% s FROM Test
6 B0 Q) v+ r( d, P/ ~( y1 U ) AS T; w& g& g, n5 W! `' L9 O
WHERE RowNum = 1;
" y7 h1 M8 u$ n& a否则,您将需要使用按ID联接到聚合的最大日期,以将结果从中筛选出来Test,仅过滤到那些日期与该ID的最大日期相匹配的对象9 W" V }' {' A
SELECT Test.Id, Test.Value, Test.ADate
4 G6 G5 a1 T* n/ |: HFROM Test
, ^0 q" p/ }7 C4 k INNER JOIN! l$ _$ v Y+ H! u1 l- x6 N; I
( SELECT ID, MAX(ADate) AS ADate8 e& Y" H7 R5 D0 Z8 u& a
FROM Test, Z. o. }/ Q M3 F
GROUP BY ID3 P" z& i7 b1 T' ?7 O4 Y: e! Y
) AS MaxT3 {4 @/ H' @: n6 H1 ]2 ~. L4 N7 \
ON MaxT.ID = Test.ID u5 x, j8 o/ P3 B6 ^0 v% Z u
AND MaxT.ADate = Test.ADate; |
|