我有这样的数据。
REPORTER SUMMARY CREATED UPDATED status servicetype
e159299 Route card from August 7/29/2013 22:46.0 5 New Route Card
e159299 I have returned the 6/11/2013 32:09.7 5 Cancel Route Card
e159324 New Route Card: RBI 1/2/2013 00:51.0 5 New Route Card
e159324 Hi, I would require 10/30/2013 35:23.0 5 New Route Card
e159299 Cancel Route Card 4/30/2013 53:26.2 5 Cancel Route Card
我需要获得特定记者的最新记录条目。 即我需要为记者做分组,并需要获得组合创建字段的最新记录。
我的输出必须是这样的。
e159299 Route card from August 7/29/2013 22:46.0 5 New Route Card
e159324 Hi, I would require 10/30/2013 35:23.0 5 New Route Card
答案 0 :(得分:3)
分析函数非常适合此类查询:
select *
from (
select reporter
, summary
, created
, updated_status
, servicetype
, max(created) over (partition by reporter) last_created
from yout_table t)
where created = last_created;
答案 1 :(得分:0)
分析函数是为此设计的 - 只需GROUP BY
相应的列(在本例中为REPORTER
),并在每个其他行上使用MAX( <column_name> ) KEEP ( DENSE_RANK LAST ORDER BY <ordering_column> )
。
Oracle 11g R2架构设置:
CREATE TABLE tbl ( REPORTER, SUMMARY, CREATED, UPDATED, status, servicetype ) AS
SELECT 'e159299', 'Route card from August', '7/29/2013', '22:46.0', 5, 'New Route Card' FROM DUAL
UNION ALL SELECT 'e159299', 'I have returned the', '6/11/2013', '32:09.7', 5, 'Cancel Route Card' FROM DUAL
UNION ALL SELECT 'e159324', 'New Route Card: RBI', '1/2/2013', '00:51.0', 5, 'New Route Card' FROM DUAL
UNION ALL SELECT 'e159324', 'Hi, I would require', '10/30/2013', '35:23.0', 5, 'New Route Card' FROM DUAL
UNION ALL SELECT 'e159299', 'Cancel Route Card', '4/30/2013', '53:26.2', 5, 'Cancel Route Card' FROM DUAL;
查询1 :
SELECT REPORTER,
MAX( SUMMARY ) KEEP ( DENSE_RANK LAST ORDER BY TO_DATE( CREATED, 'MM/DD/YYYY' ) ) AS SUMMARY,
MAX( CREATED ) KEEP ( DENSE_RANK LAST ORDER BY TO_DATE( CREATED, 'MM/DD/YYYY' ) ) AS CREATED,
MAX( UPDATED ) KEEP ( DENSE_RANK LAST ORDER BY TO_DATE( CREATED, 'MM/DD/YYYY' ) ) AS UPDATED,
MAX( status ) KEEP ( DENSE_RANK LAST ORDER BY TO_DATE( CREATED, 'MM/DD/YYYY' ) ) AS status,
MAX( servicetype ) KEEP ( DENSE_RANK LAST ORDER BY TO_DATE( CREATED, 'MM/DD/YYYY' ) ) AS servicetype
FROM tbl
GROUP BY REPORTER
<强> Results 强>:
| REPORTER | SUMMARY | CREATED | UPDATED | STATUS | SERVICETYPE |
|----------|------------------------|------------|---------|--------|----------------|
| e159299 | Route card from August | 7/29/2013 | 22:46.0 | 5 | New Route Card |
| e159324 | Hi, I would require | 10/30/2013 | 35:23.0 | 5 | New Route Card |
答案 2 :(得分:-1)
试试这个......
SELECT * FROM table ORDER BY CREATED DESC LIMIT 0,2
此查询适用于mysql数据库