plsql:在分组语句中获取另一个字段值和聚合值 [英] plsql: Getting another field values along with the aggregation values in a grouping statement

查看:470
本文介绍了plsql:在分组语句中获取另一个字段值和聚合值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究考勤系统.我将员工的交易存储在下表中:

I am working on a time attendance system. I have the employees' transactions stored in the following table:

我想获取每个雇员的最早和最新的交易,包括他们的日期类型.

I want to get the earliest and the latest transactions for each employee including their date and type.

我可以使用分组聚合获取日期.但是,我无法弄清楚如何使用它们获取 types .

I am able to get the dates using grouping and aggregation. However, I am not able to figure out how to get types with them.

请帮助我.

谢谢.

推荐答案

这是FIRST和LAST聚合函数设计的目的.

That's what the FIRST and LAST aggregate functions are designed for.

这里是文档的链接:

第一: http://下载. oracle.com/docs/cd/E11882_01/server.112/e17118/functions065.htm#SQLRF00641 上一个: http://download.oracle.com /docs/cd/E11882_01/server.112/e17118/functions083.htm#sthref1206

这是一个示例:

SQL> create table my_transactions (id,employee_id,action_date,type)
  2  as
  3  select 1, 1, sysdate, 'A' from dual union all
  4  select 2, 1, sysdate-1, 'B' from dual union all
  5  select 3, 1, sysdate-2, 'C' from dual union all
  6  select 4, 1, sysdate-3, 'D' from dual union all
  7  select 5, 2, sysdate-11, 'E' from dual union all
  8  select 6, 2, sysdate-12, 'F' from dual union all
  9  select 7, 2, sysdate-13, 'G' from dual
 10  /

Table created.

SQL> select *
  2    from my_transactions
  3   order by id
  4  /

        ID EMPLOYEE_ID ACTION_DATE         T
---------- ----------- ------------------- -
         1           1 04-07-2011 10:15:07 A
         2           1 03-07-2011 10:15:07 B
         3           1 02-07-2011 10:15:07 C
         4           1 01-07-2011 10:15:07 D
         5           2 23-06-2011 10:15:07 E
         6           2 22-06-2011 10:15:07 F
         7           2 21-06-2011 10:15:07 G

7 rows selected.

SQL> select employee_id
  2       , min(action_date) min_date
  3       , max(type) keep (dense_rank first order by action_date) min_date_type
  4       , max(action_date) max_date
  5       , max(type) keep (dense_rank last order by action_date) max_date_type
  6    from my_transactions
  7   group by employee_id
  8  /

EMPLOYEE_ID MIN_DATE            M MAX_DATE            M
----------- ------------------- - ------------------- -
          1 01-07-2011 10:15:07 D 04-07-2011 10:15:07 A
          2 21-06-2011 10:15:07 G 23-06-2011 10:15:07 E

2 rows selected.

关于,
罗布.

Regards,
Rob.

这篇关于plsql:在分组语句中获取另一个字段值和聚合值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆