除了计算出的行之外,如何选择所有行?

时间:2015-07-17 13:39:10

标签: sql oracle

假设 Table A 有1000个属性,其中一个属于 date 。我想按 last_day 选择和分组。所以如果我这样写:

 select A.*
 from db.A
 group by last_day(A.date)

它选择日期但不选择 last_day(A.date) 。我该怎么做?

3 个答案:

答案 0 :(得分:0)

SELECT  A.lastDay, A.Date
FROM    TableA A
GROUP BY A.lastDay, A.Date;

使用此查询,您可以从表中选择项目,并在2列上分组。

如果您想知道该组中有多少项,可以使用COUNT(*)

SELECT  A.lastDay, A.Date, COUNT(*)
FROM    TableA A
GROUP BY A.lastDay, A.Date;

答案 1 :(得分:0)

尝试此查询

with tab1 as(
select 1 col1, 'vish1' col2, trunc(sysdate) as tdate from dual union all
select 2 col1, 'vish2' col2, trunc(sysdate)+1 as tdate from dual union all
select 3 col1, 'vish3' col2, trunc(sysdate) as tdate from dual union all
select 4 col1, 'vish4' col2, trunc(sysdate)+1 as tdate from dual union all
select 5 col1, 'vish5' col2, trunc(sysdate) as tdate from dual 
)
select col1,col2, tdate from (
select col1,col2, tdate, row_number() over (partition by tdate order by tdate desc ) as rn from tab1)
where rn=1

这里首先我创建然后从内部查询我是基于按日期(分区)的选择记录我为每一行分配rownumber,因为他们是按日期分组,每个组中的row_number从我开始选择第一条记录;你需要使用order by子句来处理这个问题。

答案 2 :(得分:0)

对Oracel Hr架构执行示例。
Oracle / PL SQL LAST_DAY函数根据日期值返回该月的最后一天,但它不会删除时间。

select to_char(last_day(sysdate),'yyyy-mm-dd hh24:mi:ss') from dual;


select trunc(last_day(start_date)),count(1) from job_history
group by trunc(last_day(start_date));

查询计算一个月内的记录数,并按月的最后一天对其进行分组。

select trunc(last_day(start_date)),count(1) from job_history
where start_date >= trunc(last_day(start_date)) 
and start_date < trunc(last_day(start_date)) + 1
group by trunc(last_day(start_date));

查询计算每月最后一天的记录数,并按月的最后一天对其进行分组。