Calculate date differences in consecutive rows and generate a sequence
Hi Guys,
I am trying to implement one scenario where in i need to compare the date differences for consecutive rows and generate a sequence against that.
this is the table schema:
create table temp
id int identity(1,1),
emp_id int,
time datetime
insert into temp
values
(1, '2011-02-20 12:30:00.000'),
(1, '2011-02-20 12:32:34.172'),
(1, '2011-02-20 12:32:34.172'),
(1, '2011-02-20 12:43:21.004'),
(1, '2011-02-20 12:46:39.745'),
(2, '2011-02-20 12:48:06.004'),
(2, '2011-02-20 12:48:06.004'),
(2, '2011-02-20 12:53:07.733'),
(2, '2011-02-20 12:55:30.295');
now, I want to compare the first date-time with the second and so on. now if the date-time difference is same for two consecutive rows then the sequence should increment by 1 otherwise the sequence again will start from '00' for any unique date-time.
This sequence number should start from '00' from each employee.
I want the output to be like this
ID emp_id
time
sequence
1 1 2011-02-20 12:30:00.000
00
2 1 2011-02-20 12:32:34.172
00
3 1 2011-02-20 12:32:34.172
01
4 1 2011-02-20 12:32:34.172
02
5 1 2011-02-20 12:46:39.745
00
6 2
2011-02-20 12:48:06.004 00
7 2
2011-02-20 12:48:07.003 00
8 2
2011-02-20 12:48:07.003 01
9 2
2011-02-20 12:46:39.745 00
Please revert as soon as possible as this is a bit urgent.
Thank You in Advance. :)
create table temp
(id int identity(1,1),
emp_id int,
time datetime
insert into temp values
(1, '20110220 12:30:00.000'),
(1, '20110220 12:32:34.172'),
(1, '20110220 12:32:34.172'),
(1, '20110220 12:43:21.004'),
(1, '20110220 12:46:39.745'),
(2, '20110220 12:48:06.004'),
(2, '20110220 12:48:06.004'),
(2, '20110220 12:53:07.733'),
(2, '20110220 12:55:30.295');
go
SELECT id, emp_id, time,
dateadd(mcs, (row_number() OVER(PARTITION BY emp_id, time ORDER BY
id) - 1) * 10,
convert(datetime2(5), time)) AS [Sequence]
FROM temp
ORDER BY id
go
DROP TABLE temp
Erland Sommarskog, SQL Server MVP, [email protected]
Similar Messages
-
Hi,
I am new to Labview. This question might be a joke to some of you here, but any help would be greatly appreciated. I have a spreadsheet with time stamps and power outputs from a generator. I am supposed to calculate the difference between consecutive time stamps, which will act as a delay for the next power output update that needs to be sent. For example, lets say that I have to following data:
Time Stamp Power Output
11:00:00 AM 3kW
11:00:02 AM 2.9kW
11:00:04 AM 3.2kW
11:00:06 AM 3.1kW
The above data doesn't make any sense, but it is just for the purpose of this question.
So, I have to read 11:00:00 AM and 3kW initially - 3kW is the initial request that is sent. Then I have toRepeated forum post
Please view http://forums.ni.com/ni/board/message?board.id=170&message.id=294435
Regards,
Juan Galindo
Applications Engineer
National Instruments -
Days difference between current row and previous row
I was able to obtain the date in the previous row and put it in the current row as below,
EVALUATE('LAG(%1,1) OVER (ORDER BY %1)', "- Response Date".Date)
but, when I try to calculate the difference between the two dates as below, I got the error message..
TIMESTAMPDIFF(SQL_TSI_DAY, EVALUATE('LAG(%1,1) over (order by %1)',"- Response Date".Date),"- Response Date".Date)
Error message says;
_State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 30483, message: ORA-30483: window functions are not allowed here at OCI call OCIStmtExecute. [nQSError: 17010] SQL statement preparation failed. (HY000)_
Please help~ Thanks in advance, gurus~~~http://obieeone.com/2010/04/27/use-of-evaluate-function-for-analytics-function-oracle/
the link might provide you with some additional insight into the error.
Let me know if that was helpful
-bifacts
http://www.obinotes.com -
Difference between current row and previous row in a table
Hi All,
I am having a problem with the query. Can some of please help me?
I need to get difference between current row and previous row in a table. I have a table, which have data like bellow.
TABLEX
================
Name Date Items
AAA 01-SEP-09 100
BBB 02-SEP-09 101
CCC 03-SEP-09 200
DDD 04-SEP-09 200
EEE 05-SEP-09 400
Now I need to get output like bellow...
Name Date Items Diff-Items
AAA 01-SEP-09 100 0
BBB 02-SEP-09 101 1
CCC 03-SEP-09 200 99
DDD 04-SEP-09 200 0
EEE 05-SEP-09 400 200
Can some one help me to write a query to get above results?
Please let me know if you need more information.
Thanks a lot in advance.
We are using Oracle10G(10.2.0.1.0).
Thanks
Asif, nvl (items - lag (items) over (order by dt), 0)like in
SQL> with test as
2 (
3 select 'AAA' name, to_date('01-SEP-09', 'dd-MON-rr') dt, 100 items from dual union all
4 select 'BBB' name, to_date('02-SEP-09', 'dd-MON-rr') dt, 101 items from dual union all
5 select 'CCC' name, to_date('03-SEP-09', 'dd-MON-rr') dt, 200 items from dual union all
6 select 'DDD' name, to_date('04-SEP-09', 'dd-MON-rr') dt, 200 items from dual union all
7 select 'EEE' name, to_date('05-SEP-09', 'dd-MON-rr') dt, 400 items from dual
8 )
9 select name
10 , dt
11 , items
12 , nvl (items - lag (items) over (order by dt), 0)
13 from test
14 ;
NAM DT ITEMS NVL(ITEMS-LAG(ITEMS)OVER(ORDERBYDT),0)
AAA 01-SEP-09 100 0
BBB 02-SEP-09 101 1
CCC 03-SEP-09 200 99
DDD 04-SEP-09 200 0
EEE 05-SEP-09 400 200
SQL> -
Select from table in group of columns and generate a sequence number
I have to select data from a table in group of columns and generate a sequence for every group resetting the sequence to start from 1 onwards.
For example:
Data:
Col1 Col2 Col3 Col4
A NA KA 2009-08-13
B NA KA 2009-08-13
C NA KA 2009-08-13
A NA KA 2009-08-13
B NA KA 2009-08-13
A NA KA 2009-08-13
Expected output from Select Statement:
Col1 Col2 Col3 Col4 Seq_No
A NA KA 2009-08-13 1
A NA KA 2009-08-13 2
A NA KA 2009-08-13 3
B NA KA 2009-08-13 1
B NA KA 2009-08-13 2
C NA KA 2009-08-13 1
How can this be possible with a SELECT statement? Is it possible to assign seq numbers for a group of columns and reset it when it changes? In the above example, all columns form the key to generate the seq number
I know it can be done using Stored procedures and that is how I am doing it now by introducing a temporary table.
Can anyone help me in this regard? Please let me know if the question is vague to understand!
Thanks,
Nachiwith t as(select 'A' col1,'NA' col2 ,'KA' col3,'2009-08-13' col4 from dual
union all
select 'B' col1,'NA' col2 ,'KA' col3,'2009-08-13' col4 from dual
union all
select 'C' col1,'NA' col2 ,'KA' col3,'2009-08-13' col4 from dual
union all
select 'A' col1,'NA' col2 ,'KA' col3,'2009-08-13' col4 from dual
union all
select 'B' col1,'NA' col2 ,'KA' col3,'2009-08-13' col4 from dual
union all
select 'A' col1,'NA' col2 ,'KA' col3,'2009-08-13' col4 from dual)
select t.*,row_number() over (partition by col1,col2,col3,col4 order by col1,col2,col3,col4) from tYou can replace partition by col1,col2,col3,col4 with only columns that you need for grouping condition
and also order by you can just do on the column you need. -
Difference between Regular Reversal and out-of-sequence reversal
Can anyone help me understand the difference between Regular Reversal and out-of-sequence reversal? How does the system behave differently i these two reversals?
Thanks
CharleneSorry for the long reply, as here's some information that I have on Voids and Out-of-Sequence reversals.
On occasion, SAP payroll results can be created in error. In these cases, the payment never goes to the employee and the payroll result should never have been created. These cases are considered reverse payments in the off cycle workbench.
There are two forms of reverse payments: voids and out of sequence reversals. Notes 160515, 159701 and 337626 should be reviewed carefully.
An out of sequence reversal occurs when third party remittance has been run for the payroll result, or when the payroll result is not the most recent result in the cluster directory for the employee. Wage type /568 (total reversal amount) is created in the reversed result for posting purposes. Wage type /571 replaces any /559 wage types in the reversed result and the BT cluster is cleared.
Wage type /568 is created for posting purposes and it will not appear in any retros over the reversed result.
An out of sequence reversal should not occur when the employee receives the money unless the actual check is returned or the direct deposit is reversed by the bank. Because of the tax when paid principle, even if an employee writes a check back to the company for the overpaid amount, this should be processed by retro master data changes and the employee check should be used to relieve any claims in the most recent period. The claims processing guide gives details on how to relieve claims. Out of sequence reversals depend on third party remittance but not on posting to FI.
/568 - Total reversal amount - If you cancel a payroll result that A. Has had payments made to third parties or B. is other than the last one. This is considered an out of sequence reversal. If these two conditions do not apply, a true void occurs. Wage type /568 is the total reversal amount. Should be the sum of /569, /570 and /571.
/571 - Reversal of /559 - Wage type /571 is the reversal of /559 (bank transfer). /571 will record the amount from wage types /559. The /559 wage types will be deleted from the cluster that was reversed. Wage type /571 will have the same sign as wage type /559.
In payroll reporting, the reversal amounts are evaluated in the next payroll period. The same is true for posting to FI.
The out of sequence reversal should have been accompanied by a master data change that forced a retro via infotype 0003.
This retro will fix FI postings in the posting process that accompanies the retro run.For this reason, out of sequence reversals do not need an entry in table T52OCG for processing by the off cycle batch process.
Regardless of if a reverse payment is a void or an out of sequence reversal, there should be an associated master data change to perform this process properly. There had to be a reason that the payment should not have been made and this reason needs to be reflected in the employees master data. Both voids and out of sequence reversals can occur before or after the master data change, but the safest method is to perform the master data change first to ensure it occurs before the next payroll is processed.
In payroll reporting, voids are bypassed in the period for which they were originally paid. This means that if a payroll report is run for a specific period containing a void, the voided result will not be picked up. In FI, voids are bypassed in the period in which they were voided. This is possible because the off cycle batch process already reconciled any incorrect posting that occurred before the payroll result was voided.
A voided payroll result occurs when no money was given to the employee and no money was remitted through third party remittance. A void is simply a check or direct deposit that was created in error. The payroll control record was already exited and the check or direct deposit was already processed, therefore the payroll result can not be recalculated in the original period.
A void can only occur if the payroll result is the most recent result for the employee.
If the payroll result is not the most recent result, an out of sequence reversal occurs by default. It is irrelevant whether the transfer to FI has occurred or not with relation to voids. Some OSS notes state that posting to FI does matter and these notes are in error. -
Date difference between Requsition apporval and Po approval in Oracle apps
My requirement is that l need to get the number of date difference between requisition apporval date(requisition) and po approval date (purchase) excluding holidays how to do it ?
Thanks in advance..One PO could be generated from multiple requisitions. In that case, which requisition would you like to consider?
One requisition could be converted into multiple POs. In that case, which PO would you like to consider?
Assuming, there is a one-to-one relationship between your POs and requisitions:
Link a PO to the corresponding requisition by joining po_distributions_all.req_distribution_id with po_req_distributions_all.requisition_id
Once you have found the 2 records, get the approved_date from po_headers_all and po_requisition_headers_all
Then go to bom_calendar_dates for those dates and find the difference between seq_num. That is what you are looking for.
Sandeep Gandhi -
Search data in a 2d array and generate a signal when found
Hi, i am looking for an interactive way to search data from an array containing a 2d array found in a cluster. The data is in the 2d array. I have attached the vi containing the array. I want an interactive method to look up for the codes in the 2d array(found in the 1st row) and when found generate a signal to tell it has been found. The signal varies depending in which category was data code found (whether engineering, law or others). Btw the data i am looking for are in fact input using a barcode reader. Should i use a search 1d array function? or is there another method?
Solved!
Go to Solution.
Attachments:
Untitled 1.vi 6 KBJust to make sure we are totally clear here. We are trying to find the cluster which contains a certain data point in its first row of the 2D array?
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines
Attachments:
Search for element.png 14 KB -
How to display 2 dimensional data. i.e with rows and columns?
Hi,
I want to know how to display multiple, variable
rows and columns that are got from the database through
queries in forms.
(i,e. a Matrix of Values,something similar to an Excel Spreadsheet).
Is there a component in forms similar to JTABLE that is
available in Java through which MULTIPLE, VARIABLE
rows and columns can be displayed ?.
I am not using a base table since this data is got thru
a number of packages and procedures that are used in
Loops.
NOTE : I am using forms 6i.
Thanks
Sharath.I've heard Grant mention adding a Grid component to the Forms toolbox. From the context I would guess this is not yet even under development, so it's not going to be available anytime soon. And not for 6i.
Sorry, APC -
How to save data from JTable multiple rows and columns
Hi Y_Not thanks for your help before...
But what should I do if I want to get/save many data from many column and rows??i don't quite understand your (repeated) question. what is the problem with "multiple rows and columns". Y_NOT and i have shown you ways to access them.
all you need are 2 loops: one around your number of rows and one around the number of columns or vice versa depending in which order you want to save things:
for (int col = 0; col < data.size(); col++) {
for (int row = 0 ; row < data[col].size(); row++) {
// save your data
saveData(data[col].getElementAt(row));
// or use yourtable.getValueAt(row, col);
}this is not a problem of Swing/Java but of simple algorithm...
thomas -
Calculate date difference between overlapping periods
hello folks,
i am learning my way into more complex problem of java.
i have to calculate the true period lenght for a set of periods.
it is a little complidated to explain the whole business rules on this subject, but on a nutshell:
we have teams that are give a single day payment for staying in a hotel, but since this team is composed of many people (?this is a team); there are days when more then one person stays in a hotel.
we get these details at the end of a business event when all information is entered on our business intelligence system.
for a given hotel stay, the following details are submitted:
start date
end date
number of days in economic accomodation (lower class)
number of days in luxure accomodation (higher class)
if no number of days in any class, or the number is smaller then lower class is assumed to be the one used
another business rule says that for the first night out (away from their home) staff receives an extra night for their transfer (!generous company!)
i have created a class for holding all this information so far - HotelStay.java
since this is a team information for a given business event i receive anything between 0 to 200 hotel stays.
thus my dataset looks like
teamID
hotelStayStartDt
hotelStayEndDt
daysInLowerClass
daysInHigherClass
my objective are:
to be able to calculate the actual number of stays (including any additions for the first day away)
to be able to calculate number of total days - including over laps - these will be paid in a different rate)
number of days in each hotel class - lower and higher
since i am clueless how to go about it, i would really appreciate assistance here.
below is my HotelStay.java
many thanks,
Nichere is the class that i have created so far
package businessCalculations.awayStays;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import com.sun.org.apache.xalan.internal.xsltc.trax.SmartTransformerFactoryImpl;
import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor.SetterOnlyReflection;
* @author
public class HotelStay {
* hotel starting date of stay hotel stays can only start in the past or
* today as this is not processing future bookings only dates over and above
* 1990 are considered into this system
private Date hotelStayStartDt;
* hotel date end of staying only dates over and above 1990 are considered
* into this system
private Date hotelStayEndDt;
* days for which a person stayed in economic or other lower class
* accommodation
private int daysInLowerClass = 0;
* days for which a person stayed in de-luxe or other higher class
* accommodation
private int daysInHigherClass = 0;
* flags when person was sleeping in another hotel at the beginning of this
* stay (they went from one hotel to another without going home in betwee
* if they were they do not receive the added day bonus for transfer
* (one overnight stay <b>EXTRA</b>) thus if at the beginning of the stay,
* they were not sleeping in another hotel, they receive an extra night for
* their transfer
private boolean isSleepingAwayOverlapping = false;
* default constructor
* @param hotelStayStartDt
* @param hotelStayEndDt
* @param daysInLowerClass
* @param daysInHigherClass
public HotelStay(Date hotelStayStartDt, Date hotelStayEndDt,
int daysInLowerClass, int daysInHigherClass) {
boolean outcome = this.addNewHotelStay(hotelStayStartDt, hotelStayEndDt, daysInLowerClass, daysInHigherClass);
* @param hotelStayStartDt
* @param hotelStayEndDt
* @param daysInLowerClass
* @param daysInHigherClass
* @return
public boolean addNewHotelStay(Date hotelStayStartDt, Date hotelStayEndDt, int daysInLowerClass, int daysInHigherClass) {
if (this.isValidStayDt(hotelStayStartDt) && this.isValidStayDt(hotelStayEndDt)){
int lengthOfStay = this.getLengthOfStay(hotelStayStartDt, hotelStayEndDt);
if(lengthOfStay >=1) {
this.setHotelStayStartDt(hotelStayStartDt);
this.setHotelStayEndDt(hotelStayEndDt);
if (
(daysInHigherClass + daysInLowerClass == 0)
|| (daysInHigherClass + daysInLowerClass <= lengthOfStay + 1 )
this.setDaysInLowerClass(daysInLowerClass);
this.setDaysInHigherClass(daysInHigherClass);
} else {
this.setDaysInLowerClass(daysInLowerClass);
this.setDaysInHigherClass(daysInHigherClass);
return true;
}else{
return false;
* @return the admissionDt
private Date getHotelStayStartDt() {
return this.hotelStayStartDt;
* @param admissionDt
* the admissionDt to set
private void setHotelStayStartDt(Date admissionDt) {
this.hotelStayStartDt = admissionDt;
* @return the dischargeDt
private Date getHotelStayEndDt() {
return this.hotelStayEndDt;
* @param dischargeDt
* the dischargeDt to set
private void setHotelStayEndDt(Date dischargeDt) {
this.hotelStayEndDt = dischargeDt;
* @return the isOverlappingOtherCcStays
private boolean isOverlappingOtherCcStays() {
return this.isSleepingAwayOverlapping;
* @param isOverlappingOtherCcStays
* the isOverlappingOtherCcStays to set
private void setOverlappingOtherCcStays(boolean isOverlappingOtherCcStays) {
this.isSleepingAwayOverlapping = isOverlappingOtherCcStays;
* @return the daysInLowerClass
private int getDaysInLowerClass() {
return this.daysInLowerClass;
* @param daysInLowerClass
* the daysInLowerClass to set
private void setDaysInLowerClass(int daysInLowerClass) {
this.daysInLowerClass = daysInLowerClass;
* @return the daysInHigherClass
private int getDaysInHigherClass() {
return this.daysInHigherClass;
* @param daysInHigherClass
* the daysInHigherClass to set
private void setDaysInHigherClass(int daysInHigherClass) {
this.daysInHigherClass = daysInHigherClass;
* @return the isSleepingAwayOverlapping
private boolean isSleepingAwayOverlapping() {
return this.isSleepingAwayOverlapping;
* @param isSleepingAwayOverlapping
* the isSleepingAwayOverlapping to set
private void setSleepingAwayOverlapping(boolean isSleepingAwayOverlapping) {
this.isSleepingAwayOverlapping = isSleepingAwayOverlapping;
@Override
public String toString() {
String rtn = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy hh:mm");
String inDt = sdf.format(getHotelStayStartDt());
String outDt = sdf.format(getHotelStayEndDt());
rtn = "ArrivalDt("
+ (inDt.isEmpty() ? "" : inDt) + ")\t,BookOutDt("
+ (outDt.isEmpty() ? "" : outDt) + ")\t,DaysInLowerClass ("
+ String.valueOf(getDaysInLowerClass())
+ ")\t,DaysInHigerClass ("
+ String.valueOf(getDaysInHigherClass()) + ")";
return rtn;
public int getLengthOfStay(Date hotelStayStartDt, Date hotelStayEndDt ){
Calendar startDt = new GregorianCalendar();
startDt.setTime(hotelStayStartDt);
Calendar endDt = new GregorianCalendar();
endDt.setTime(hotelStayEndDt);
long startMill = startDt.getTimeInMillis();
long endMill = endDt.getTimeInMillis();
// Calculate difference in days
// divided by (24 hours, 60 minutes, 60 seconds, 1000 milliseconds
// casted as (int)
return (int) ((endMill - startMill) / (24 * 60 * 60 * 1000));
private boolean isValidStayDt(Date aDate) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy");
Calendar minDt = new GregorianCalendar();
Calendar maxDt = new GregorianCalendar();
maxDt.add(Calendar.DATE, +1);
try {
minDt.setTime(sdf.parse("01/jan/1990"));
} catch (ParseException e) {
e.printStackTrace();
if (aDate.after(minDt.getTime()) && aDate.before(maxDt.getTime())) {
return true;
} else {
return false;
}Edited by: www.jegue.net on Jul 17, 2010 11:31 AM -
Compare dates between 2 different rows and columns
I'm having problems figuring this out. Here is an example table:
What I need to be able to find is any records where the Discontinue_Date is greater than the Effective_Date on the next row for a given Customer ID and Part_ID. This is a customer pricing table so the Discontinue_Date of row 53 for example should never
be greater than the Effective_Date of row 54130, these are the records I'm looking to find. So I'm looking for a SELECT query that would look for any records where this is true. Obviously the last Discontinue_Date row for a Customer_ID will not
have a next row so I wouldn't want to return that.
Let me know if anyone has any ideas or if more clarification is needed, I've been struggling with how to get started on this!!
Thanks very much in advance!
JIM>> I'm having problems figuring this out. Here is an example table: <<
NO! Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data
should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. You pasted a colored picture that we have to transcribe into DDL to do your job for you. But you also do not know basic terminology!
Rows are not records, since tables are sets, there is no “next row” concept, rows do not have physical row numbers, etc. Your mindset is still in a spreadsheet and not RDBMS.
>> What I need to be able to find is any records [sic] where the discontinuation_date is greater than the effective_date on the next row for a given customer_id and part_id. <<
Why not prevent bad data instead of trying to kludge and report it after the fact?
Consider this self-reference trick to prevent gaps in a timeline of events:
CREATE TABLE Events
(event_id CHAR(10) NOT NULL,
previous_event_end_date DATE NOT NULL
CONSTRAINT Chained_Dates
REFERENCES Events (event_end_date),
event_start_date DATE NOT NULL,
event_end_date DATE UNIQUE, -- null means event in progress
PRIMARY KEY (event_id, event_start_date),
CONSTRAINT Event_Order_Valid
CHECK (event_start_date <= event_end_date),
CONSTRAINT Chained_Dates
CHECK (DATEADD(DAY, 1, previous_event_end_date) = event_start_date).
<< other stuff for this event >>
-- disable the Chained_Dates constraint
ALTER TABLE Events NOCHECK CONSTRAINT Chained_Dates
-- insert a starter row
INSERT INTO Events(event_id, previous_event_end_date, event_start_date, event_end_date)
VALUES ('Foo Fest', '2010-01-01', '2010-01-02', '2010-01-05');
-- enable the constraint in the table
ALTER TABLE Events CHECK CONSTRAINT Chained_Dates
-- this works
INSERT INTO Events(event_id, previous_event_end_date, event_start_date, event_end_date)
VALUES ('Glob Week', '2010-01-05', '2010-01-06', '2010-01-10');
-- this fails
INSERT INTO Events(event_id, previous_event_end_date, event_start_date, event_end_date)
VALUES ('Snoob', '2010-01-09', '2010-01-11', '2010-01-15');
Since you did not write DDL for us, you can use this idiom to get a working schema.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
How can I calculate the count of each row and they are grouped in each mth?
hi, I need help on a database question. How can I count the number of record grouped by the last 12 months? I don't know any way to iterate the month one by one so that it return a table like this:
table_item
id item
1 A
2 B
3 C
4 D
table_record
item date
A 2006-01-01
A 2006-01-01
A 2006-01-01
B 2006-02-01
A 2006-03-01
C 2006-04-01
A 2006-04-01
D 2006-05-01
A 2006-05-01
A 2006-12-01
and I need a query to output following table:
item_count_in_2006
item 06-01 06-02 06-03 06-04 06-05 06-06 06-07 06-08 06-09 06-10 06-11 06-12
A 3 1 1
B 1
C 1
D 1
I tried so many way to do it.. I think SQL can't even product a table like that. Please give me some comments.
Thanks!select c1,
count(decode(to_char(c2,'YYYYMM'),'200601',1)) "200601",
count(decode(to_char(c2,'YYYYMM'),'200602',1)) "200602",
count(decode(to_char(c2,'YYYYMM'),'200603',1)) "200603",
count(decode(to_char(c2,'YYYYMM'),'200604',1)) "200604",
count(decode(to_char(c2,'YYYYMM'),'200605',1)) "200605",
count(decode(to_char(c2,'YYYYMM'),'200606',1)) "200606",
count(decode(to_char(c2,'YYYYMM'),'200607',1)) "200607",
count(decode(to_char(c2,'YYYYMM'),'200608',1)) "200608",
count(decode(to_char(c2,'YYYYMM'),'200608',1)) "200609",
count(decode(to_char(c2,'YYYYMM'),'200610',1)) "200610",
count(decode(to_char(c2,'YYYYMM'),'200611',1)) "200611",
count(decode(to_char(c2,'YYYYMM'),'200612',1)) "200612"
from tbl
group by c1
C 200601 200602 200603 200604 200605 200606 200607 200608 200609 200610
D 0 0 0 0 1 0 0 0 0 0 0 0
A 3 0 1 1 1 0 0 0 0 0 0 1
B 0 1 0 0 0 0 0 0 0 0 0 0
C 0 0 0 1 0 0 0 0 0 0 0 0Nicolas. -
Data difference between PSA/Query and InfoCube
Hi All!
I have a problem during the data extraction from R/3 to a basic Cube. When the currency is different from EUR, the key figure 0CS_YTD_TC data its different from the others (0CS_YTD_GC and 0CS_YTD_LC). In the cube content the value is correct but in the PSA and in queries is not.
What can I do?Ricardo,
Do you mean that one of your KF value (for example, in the cube) differs from the value shown in a query 10 times?
If so, look at the table TCURX. In my system PTE has 0 decimals. It means that cube/query will differ 100 times.
Look here at the problem description:
Re: Local Currency COP, KRW values wrong in report
and here for workaround on a query level:
Re: is conditional calculation in the report possible?
Best regards,
Eugene -
Get data from PL/SQL block and generate the data file in UNIX
Hi All
i was executing the following code block from Unix Shell Script. The following code was generating the file count_curdate.txt with all require infomrations. The query gives number of records , group by partition_dt
ABC=`sqlplus -s <<EOF > count_curdate.txt
uname/paswd@connectstring
SET HEADING OFF;
SELECT COUNT(*)||','||partition_dt from XYZ group by partition_dt;
exit;
END`
But now i need to change the above code to use dbms_application_info.set_module in it. Could someone let me know how to generate the file using PL/SQL block in Shell Script. I tried writing following code, but it generate count_curdate.txt file with 0 bytes.
ABC=`sqlplus -s <<EOF > count_curdate.txt
uname/paswd@connectstring
set serveroutput on;
SET HEADING OFF;
set feedback off;
BEGIN
dbms_application_info.set_module ('shm.ksh','get count by day');
FOR reccur IN (SELECT COUNT(*)||','||partition_dt as "dcount" from XYZ group by partition_dt);
LOOP
DBMS_OUTPUT.PUT_LINE(reccur.dcount);
END LOOP;
end;
exit;
END`OK, try this:
ABC=`sqlplus -s <<EOF > count_curdate.txt
uname/paswd@connectstring
set serveroutput on;
SET HEADING OFF;
set feedback off;
BEGIN
dbms_application_info.set_module ('shm.ksh','get count by day');
FOR reccur IN (SELECT COUNT(*)||','||partition_dt dcount from XYZ group by partition_dt);
LOOP
DBMS_OUTPUT.PUT_LINE(reccur.dcount);
END LOOP;
dbms_application_info.set_module (NULL,NULL);
end;
exit;
EOF`Or this:
ABC=`sqlplus -s <<EOF > count_curdate.txt
uname/paswd@connectstring
set serveroutput on;
SET HEADING OFF;
set feedback off;
BEGIN
dbms_application_info.set_module ('shm.ksh','get count by day');
END;
SELECT COUNT(*)||','||partition_dt dcount from XYZ group by partition_dt;
BEGIN
dbms_application_info.set_module (NULL,NULL);
END;
exit;
EOF`Edited by: SeánMacGC on May 11, 2009 6:13 AM
Maybe you are looking for
-
Cant resolve the host name in mac
cant resolve your hostname then do the following work around: sudo vi /private/etc/hosts create the entry with IP and hostname ....no need of domain..
-
Recording of the payment condition in the table RBKP
They would know how to say because in the moment in that are making IV (invoice verification) the payment condition is not recorded in the table RBKP. In the table we have the field even so nothing is not recorded. Tanks Joubert Carvalho
-
Hi All, Implementation Scenario: Extended Classic Scenario User has created shopping cart and then raised PO,now he found that he wants to do some changes say new vendor or supplier to be assigned.User has now cancelled / deleted a PO.Now we should
-
Value Based Hierarchy in OBI EE
Hello, In OBI SE we use both value-based and level-based hierarchies. But in EE I can't find an opportunity to use value based hierarchy. How to use value based hierarchy (parent-child) in OBI EE?
-
I can't run the installer file because a padlock appears in Mac OS X Yosemite.
When I download the file it appears on Finder with a padlock in the upper left corner. If I try to run it, it opens with another program that can't read it. Looking for some information on the internet I read something about the file permissions. But