Need a rolling count of rows from table using just SQL
Oracle 11gR2
RHEL 6.4
Given the following table data:
EMPLOYEE HIRE_DATE TERM_DATE DEPT
John Doe 01/01/13 101
Jane Smith 01/05/13 102
Bob Jones 02/04/13 04/22/13 102
Jenny Boo 03/12/13 03/31/13 103
Joe Schmoe 03/24/13 102
Bill Max 04/23/13 103
Jill Clay 04/24/13 103
Joe Boom 05/11/13 102
I want to return the number of employees that are still employed for each month so long as they were hired anytime in that month and irregardless if they were terminated later that month (i.e only the month concerns me). So I would be expecting
MONTH EMPLOYEES
Jan 2
Feb 3
Mar 5
Apr 6 (Jenny Boo has been terminated)
May 6 (Jenny Boo and Bob Jones have been terminated)
I know there are some bright people out there that are SQL experts but I am not one of them. If there is a way to do this in just SQL I would like to see it.
Assuming you want count just for months where someone was hired or terminated:
with t as (
select trunc(hire_date,'mm') dt,
1 weight
from emp1
union all
select last_day(term_date) + 1 dt,
-1 weight
from emp1
where term_date is not null
select to_char(dt,'FMMonth, YYYY') month,
sum(sum(weight)) over(order by dt) employees
from t
group by dt
order by dt
MONTH EMPLOYEES
January, 2013 2
February, 2013 3
March, 2013 5
April, 2013 6
May, 2013 6
SQL>
If you want all months within given range:
with r as (
select date '2013-03-01' from_dt,
date '2013-12-01' to_dt
from dual
t as (
select trunc(hire_date,'mm') dt,
1 weight,
from_dt
from emp1,
r
where hire_date <= last_day(to_dt)
union all
select last_day(term_date) + 1 dt,
-1 weight,
from_dt
from emp1,
r
where last_day(term_date) + 1 <= to_dt
union all
select add_months(from_dt,level - 1) dt,
0 weight,
from_dt
from r
connect by add_months(from_dt,level - 1) <= to_dt
s as (
select dt,
sum(sum(weight)) over(order by dt) employees,
from_dt
from t
group by dt,
from_dt
select to_char(dt,'FMMonth, YYYY') month,
employees
from s
where dt >= from_dt
order by dt
MONTH EMPLOYEES
March, 2013 5
April, 2013 6
May, 2013 6
June, 2013 6
July, 2013 6
August, 2013 6
September, 2013 6
October, 2013 6
November, 2013 6
December, 2013 6
10 rows selected.
SQL>
SY.
Similar Messages
-
Newbie question: Select one row from table in PL/SQL
Hi,
I want to select one row from the table Employee where Emplyoyee Number is say 200. This is a simple SQL query, but I don't know the equivalent PL/SQL format. I will have 3 out params here - Id itself, Name, Salary. I will then have to populate a java resultset object from these out params.
Later, I'll have to use cursors to retrieve more than one row.
Thanks for any help.Perhaps something like
CREATE OR REPLACE PROCEDURE get_employee( l_id IN OUT employee.id%TYPE,
l_name OUT employee.name%TYPE,
l_salary OUT employee.salary%TYPE )
AS
BEGIN
SELECT name, salary
INTO l_name, l_salary
FROM employee
WHERE id = l_id;
END;Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Count of rows from different tables.
Hi Friends,
I have 4 tables with a common column name "ID". I would like to get the count of rows from all the four tables which has the same ID.
Ex
select count(a.id) from table1 a,table2 b,table3 c,table4 d where a.id=b.id=c.id=d.id=5;
please suggest me some solutionmay be thsi?
select count(a.id) from table1 a,table2 b,table3 c,table4 d
where a.id=b.id and a.id=c.id and a.id=d.id and a.id=5; -
I need a resultset with 10 rows from dual
Which is the easiest SELECT I have to write, when the question is: "I need a resultset with 10 rows from dual"
one solution is
SELECT 'X' FROM EMP WHERE ROWNUM <= 10;
problem: if emp has fewer than 10 rows, I have an incorrect resultset
another problem: if I need 1000 and not 10 dummy-rows, than is emp definitely the wrong way, because the default-emp table has only 14 rows.
Is there an easy generic solution for this problem? If I need only one row, Oracle has the workaround with the DUAL-table.What about this new method (dedicated by me to this great FORUM!). It is easy to use, easy to understand, and very fast:
SQL> set echo on
SQL> set timing on
SQL> select rownum
2 from all_objects
3 where rownum <=10;
ROWNUM
1
2
3
4
5
6
7
8
9
10
10 rows selected.
Elapsed: 00:00:00.00
SQL> select COUNT(rownum)
2 from all_objects
3 where rownum <=1000;
COUNT(ROWNUM)
1000
Elapsed: 00:00:00.00
SQL> with r1000
2 as (select rownum
3 from all_objects
4 where rownum <=1000)
5 select count(rownum)
6 from r1000, r1000
7 where rownum <= 1000000;
COUNT(ROWNUM)
1000000
Elapsed: 00:00:00.05 -- !for 1 million numbers!
SQL> with r1000
2 as (select rownum
3 from all_objects
4 where rownum <=1000)
5 select count(rownum)
6 from r1000, r1000, r1000
7 where rownum <= 10000000;
COUNT(ROWNUM)
10000000
Elapsed: 00:00:04.09 -- !for 10 millions numbers! -
Deleting rows from table based on value from other table
Hello Members,
I am struck to solve the issue said below using query. Would appreciate any suggestions...
I have two tables having same structures. I want to delete the rows from TableA ( master table ) with the values from TableB ( subset of TableA). The idea is to remove the duplicate values from tableA. The data to be removed are present in TableB. Catch here is TableB holds one row less than TableA, for example
Table A
Name Value
Test 1
Test 1
Test 1
Hello 2
Good 3
TableB
Name Value
Test 1
Test 1
The goal here is to remove the two entries from TableB ('Test') from TableA, finally leaving TableA as
Table A
Name Value
Test 1
Hello 2
Good 3
I tried below queries
1. delete from TestA a where rowid = any (select rowid from TESTA b where b.Name = a.Name and a.Name in ( select Name from TestB ));
Any suggestions..
We need TableB. The problem I mentioned above is part of process. TableB contains the duplicate values which should be deleted from TableA. So that we know what all values we have deleted from TableA. On deleted TableA if I later insert the value from TableB I should be getting the original TableA...
Thanks in advancedrop table table_a;
drop table table_b;
create table table_b as
select 'Test' name, 1 value from dual union all
select 'Test' ,1 from dual;
create table table_a as
select 'Test' name, 1 value from dual union all
select 'Test' ,1 from dual union all
select 'Test' ,1 from dual union all
select 'Hello' ,2 from dual union all
select 'Good', 3 from dual;
/* Formatted on 11/23/2011 1:53:12 PM (QP5 v5.149.1003.31008) */
DELETE FROM table_a
WHERE ROWID IN (SELECT rid
FROM (SELECT ROWID rid,
ROW_NUMBER ()
OVER (PARTITION BY name, VALUE
ORDER BY NULL)
rn
FROM table_a a
WHERE EXISTS
(SELECT 1
FROM table_b b
WHERE a.name = b.name
AND a.VALUE = b.VALUE))
WHERE rn > 1);
select * from table_a
NAME VALUE
Test 1
Hello 2
Good 3Edited by: pollywog on Nov 23, 2011 1:55 PM -
How to update duplicate row from table
Hi,
how to update duplicate row from table?
First to find duplicate row then update duplicate row with no to that duplicate row in oracle.
can you give me suggestion on it?
Thanks in advance.
your early response is appreciated...In order to find a duplicate row, see:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1224636375004
(or search this forum, your question has been asked before)
In order to update it, just create and use an Oracle sequence, have it start and increment at a value that doesn't exist in your table.
If that doesn't get you going, post some CREATE TABLE + INSERT INTO statements, and the results you want from them, in other words: a complete testcase. -
How to delete a single data from table using control file
I want delete a single row data from table using sql loder control file
Edited by: 977940 on Dec 19, 2012 9:00 PM977940 wrote:
I want delete a single row data from table using sql loder control file
Edited by: 977940 on Dec 19, 2012 9:00 PMWhy?
And how do you imagine this happening with sqlloader?
The entire purpose of sqlloader is to load data (hence, the name sql*loader*) into a table from an external source. If you want to delete rows from a table, you use the sql DELETE statement.
What is the business problem you are trying to solve? -
Loading the data from a text file to a table using pl/sql
Hi Experts,
I want to load the data from a text (sample1.txt) file to a table using pl/sql
I have used the below pl/sql code
declare
f utl_file.file_type;
s varchar2(200);
c number := 0;
begin
f := utl_file.fopen('TRY','sample1.txt','R');
loop
utl_file.get_line(f,s);
insert into sampletable (a,b,c) values (s,s,s);
c := c + 1;
end loop;
exception
when NO_DATA_FOUND then
utl_file.fclose(f);
dbms_output.put_line('No. of rows inserted : ' || c);
end;
and my sample1.txt file looks like
1
2
3
The data is getting inserted, with below manner
select * from sampletable;
A B C
1 1 1
2 2 2
3 3 3
I want the data to get inserted as
A B C
1 2 3
The text file that I have is having three lines, and each line's first value should go to each column
Please help...
Thanksdeclare
f utl_file.file_type;
s1 varchar2(200);
s2 varchar2(200);
s3 varchar2(200);
c number := 0;
begin
f := utl_file.fopen('TRY','sample1.txt','R');
utl_file.get_line(f,s1);
utl_file.get_line(f,s2);
utl_file.get_line(f,s3);
insert into sampletable (a,b,c) values (s1,s2,s3);
c := c + 1;
utl_file.fclose(f);
exception
when NO_DATA_FOUND then
if utl_file.is_open(f) then utl_file.fclose(f); ens if;
dbms_output.put_line('No. of rows inserted : ' || c);
end;SY. -
How to find max(time) from table using group by
how to find max(time) from table using group by
select var max(time)
from table
into (var1, time1)
where .....
group by var.
it is fetching record which is top in table.
if u can help?
regards.No this will fetch the maximum time from teh table.
select var max(time)
from table xxxx
into (var1, time1)
where .....
group by var.
Refer this code
TABLES SBOOK.
DATA: COUNT TYPE I, SUM TYPE P DECIMALS 2, AVG TYPE F.
DATA: CONNID LIKE SBOOK-CONNID.
SELECT CONNID COUNT( * ) SUM( LUGGWEIGHT ) AVG( LUGGWEIGHT )
INTO (CONNID, COUNT, SUM, AVG)
FROM SBOOK
WHERE
CARRID = 'LH ' AND
FLDATE = '19950228'
GROUP BY CONNID.
WRITE: / CONNID, COUNT, SUM, AVG.
ENDSELECT. -
HT201250 I need to retrieve my Quicken folder from yesterday using Time Machine. How?
I need to retrieve my Quicken folder from yesterday using Time Machine. How?
You have to know where Quicken stores it (I don't use Quicken, so don't know myself). It's probably somewhere in either the Documents folder or the Application Support folder inside the Library folder in your home folder.
Once you find where it is, see either the Time Machine Tutorial, or Time Machine - Frequently Asked Question #15 for restore instructions. -
How can one read a Excel File and Upload into Table using Pl/SQL Code.
How can one read a Excel File and Upload into Table using Pl/SQL Code.
1. Excel File is on My PC.
2. And I want to write a Stored Procedure or Package to do that.
3. DataBase is on Other Server. Client-Server Environment.
4. I am Using Toad or PlSql developer tool.If you would like to create a package/procedure in order to solve this problem consider using the UTL_FILE in built package, here are a few steps to get you going:
1. Get your DBA to create directory object in oracle using the following command:
create directory TEST_DIR as ‘directory_path’;
Note: This directory is on the server.
2. Grant read,write on directory directory_object_name to username;
You can find out the directory_object_name value from dba_directories view if you are using the system user account.
3. Logon as the user as mentioned above.
Sample code read plain text file code, you can modify this code to suit your need (i.e. read a csv file)
function getData(p_filename in varchar2,
p_filepath in varchar2
) RETURN VARCHAR2 is
input_file utl_file.file_type;
--declare a buffer to read text data
input_buffer varchar2(4000);
begin
--using the UTL_FILE in built package
input_file := utl_file.fopen(p_filepath, p_filename, 'R');
utl_file.get_line(input_file, input_buffer);
--debug
--dbms_output.put_line(input_buffer);
utl_file.fclose(input_file);
--return data
return input_buffer;
end;
Hope this helps. -
How to read XML message present in Table using PL/SQL?
Hi,
How to read XML content present in Table using PL/SQL .And is it possible to parse the xml uisng xslt and insert xml output in same table again ?
Thanks!Late reply, but hopefully better late than never.
You can possibly do it all via a single SQL statement, such as {message:id=4232077}
XMLTable Syntax can be found at http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions228.htm#CIHGGHFB (for 10.2 users) else find your correct version at http://www.oracle.com/technology/documentation/index.html -
Hi All,
I have implemented paging on huge list. Grid gets shown 20 items per page but I have to show on grid pager a total count of items. Moreover filters could be applied to the grid. So, total count will depend from filter criteria. What is best approach to do
something similar to SQL select count (*) from sometable on SharePoint list?
OlegHi,
According to your description, you want to get the total count of items in current list view.
There is an OTTB feature “Totals” in the list view settings, it can count the items existing in the current list view.
I suggest you do as the followings:
1. Set the total count for the column in the list view->”Totals”.
Then, the total item count will show in the list.
Best regards -
How to hide row from table after logical delete
Hello.
I am using Jdeveloper 11.1.1.3.0, ADF BC and ADF Faces.
I want to implement Logical delete in my application.
In my Entity object I have Deleted attribute and I override the remove() method in my EntityImpl class.
@Override
public void remove()
setDeleted("Y");
}and I added this condition to my view object
WHERE NVL(Deleted,'N') <> 'Y'in my page I have a table. this table has a column to delete each row. I dragged and drop RemoveRowWithKey action from the data control
and set the parameter to *#{row.rowKeyStr}* .
I what I need is this:
when the user click the delete button I want to hide the roe from the table. I tried to re-execute the query after the delete but the row is still on the page. Why execute query does not hide the row from the screen.
here is the code I used for delete and execute query
public String deleteLogically()
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("removeRowWithKey");
Object result = operationBinding.execute();
DCBindingContainer dc=(DCBindingContainer) bindings;
DCIteratorBinding iter=dc.findIteratorBinding("TakenMaterialsView4Iterator");
iter.getCurrentRow().setAttribute("Deleted", "Y");
//iter.getViewObject().executeQuery();
iter.executeQuery();
return null;
}as you see I used two method iter.getViewObject().executeQuery(); and iter.executeQuery(); but the result is same.Thank you Jobinesh.
I used this method.
@Override
protected boolean rowQualifies(ViewRowImpl viewRowImpl)
Object attrValue =viewRowImpl.getAttribute("Deleted");
if (attrValue != null) {
if ("Y".equals(attrValue))
return false;
else
return true;
return super.rowQualifies(viewRowImpl);
}But I have one drawback for using it, and here is the case:
If the user clicks the delete button *(no commit)* the row will be hidden in the table, but when the user click cancel changes the row is not returned since it is not returned due to the rowQualifies(ViewRowImpl viewRowImpl) (the Deleted attribute is set to "N" now).
here is the code for delete and cancel change buttons
public String deleteLogically()
BindingContainer bindings = getBindings();
OperationBinding operationBinding =
bindings.getOperationBinding("removeRowWithKey");
Object result = operationBinding.execute();
DCBindingContainer dc = (DCBindingContainer)bindings;
DCIteratorBinding iter =
dc.findIteratorBinding("TakenMaterialsView4Iterator");
iter.getCurrentRow().setAttribute("Deleted", "Y");
iter.executeQuery();
AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
adfFacesContext.addPartialTarget(this.getTakenMaterialsTable());
return null;
public String cancelChanges(String iteratorName)
System.out.println("begin cancel change");
BindingContainer bindings =
BindingContext.getCurrent().getCurrentBindingsEntry();
DCBindingContainer dc = (DCBindingContainer)bindings;
DCIteratorBinding iter =
(DCIteratorBinding)dc.findIteratorBinding(iteratorName);
ViewObject vo = iter.getViewObject();
//create a secondary RowSetIterator to avoid disturbing row currency
RowSetIterator rsi = vo.createRowSetIterator(null);
//move the currency to the slot before the first row.
rsi.reset();
while (rsi.hasNext())
currentRow = rsi.next();
currentRow.setAttribute("Deleted", "N");
rsi.closeRowSetIterator();
iter.executeQuery();
AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
adfFacesContext.addPartialTarget(this.getTakenMaterialsTable());
return null;
}as example, if the user initially has 8 rows, then deleted 2 rows, in cancelChanges only 6 rows appears. and the deleted rows are not there??
any suggestion? -
Deleting row from table in ABAP webdynpro
Hi all,
Can anyone help me regarding deletion of a row from a table in ABAP webdynpro.
I have written a code like this :
DATA:
NODE_STUDINFOSYS TYPE REF TO IF_WD_CONTEXT_NODE,
ELEM_STUDINFOSYS TYPE REF TO IF_WD_CONTEXT_ELEMENT,
STRU_STUDINFOSYS TYPE IF_COMPONENTCONTROLLER=>ELEMENT_STUDINFOSYS .
navigate from <CONTEXT> to <STUDINFOSYS> via lead selection
NODE_STUDINFOSYS = WD_CONTEXT->GET_CHILD_NODE( NAME = IF_COMPONENTCONTROLLER=>WDCTX_STUDINFOSYS ).
get element via lead selection
ELEM_STUDINFOSYS = NODE_STUDINFOSYS->GET_ELEMENT( ).
deleting data selected via lead selection
NODE_STUDINFOSYS->REMOVE_ELEMENT( ELEMENT = ELEM_STUDINFOSYS ).
*But I am getting an error:*
Error when processing your request
What has happened?
The URL http://hsdnt24s11.hclt.corp.hcl.in:8000/sap/bc/webdynpro/sap/znet310_add_del_sech/ was not called due to an error.
Note
The following error text was processed in the system HE6 : The lead selection has not been set. VIEW_ADD_DEL_01
The error occurred on the application server hsdnt24s11_HE6_00 and in the work process 0 .
The termination type was: RABAX_STATE
The ABAP call stack was:
Method: RAISEELEMENT_NOT_FOUND of program CL_WDR_CONTEXT_NODE===========CP
Method: PATH_TABLE_GET_ELEMENT2 of program CL_WDR_CONTEXT_NODE===========CP
Method: GET_BOUND_ELEMENT of program CL_WDR_VIEW_ELEMENT_ADAPTER===CP
What can I do?
If the termination type was RABAX_STATE, then you can find more information on the cause of the termination in the system HE6 in transaction ST22.
If the termination type was ABORT_MESSAGE_STATE, then you can find more information on the cause of the termination on the application server hsdnt24s11_HE6_00 in transaction SM21.
If the termination type was ERROR_MESSAGE_STATE, then you can search for more information in the trace file for the work process 0 in transaction ST11 on the application server hsdnt24s11_HE6_00 . In some situations, you may also need to analyze the trace files of other work processes.
If you do not yet have a user ID, contact your system administrator.
Error code: ICF-IE-http -c: 800 -u: SUMANK -l: E -s: HE6 -i: hsdnt24s11_HE6_00 -w: 0 -d: 20081220 -t: 155832 -v: RABAX_STATE -e: UNCAUGHT_EXCEPTION
HTTP 500 - Internal Server Error
Your SAP Internet Communication Framework Team
Can anyone help me???Hi Suman,
this issue seems to be not specific to the FPM. I would like to suggest you to address this problem in the ABAP forum.
Best regards,
Thomas
Maybe you are looking for
-
A Voice Memo item has appeared in main menu and I cannot remove it. When I go to *settings>main menu* no such item is listed so I cannot deselect it. Any ideas appreciated...
-
Problem in instation of 10g release 1 databse on RHEL 4
I install oracle 10g on RHEL 4. But error occure in cofiguration assistant. following assistance not configured (which are recommended): Oracle Net Configuration Assistant - fail HTTP Server Configuration Assitant - skipped Java Security Configuratio
-
I can't remember my password to my itunes or app account or the security questions,
I can't remember my password to my itunes or app account or the security questions,
-
The bookstore and Tomcat 4 are not good together
Hi all, I thought I will never have any problems with Java Tutorials, but it happens.. I am stuck with the Servel tutorial, 1) I have Tomcat 4.0 up and running; that is http://localhost:8080 shows me tomcat welcome message. 2) I've downloaded the tut
-
Hi All, How do I display the hierarchy in my report in expanded manner by default? when I execute my query the report comes with the higher node. I manually expand the hierarchy by right clicking on it. I want to display all the nodes expanded by def