Alert based on a value of previous row
Hello there
On a db level there are analytical functions 'LOG' which allows to compare the previous value, but my task is to create the alerter which sends e-mail if next value is greater than current one.
I know that there is a functions previous() etc, but how to implement this, maybe smb can elighten me on this.
Example:
ID DATE TRANSACTION COUNT
1 01.01.2014 1120
2 02.01.2014 1099
3 03.01.2014 1700 --> Alert is triggered
SO, for the last value alert has to be triggered and sent to E-mail. On DB level i see no problems implementing this, but how to implement this in Crystal?
One option is to create or get a Crystal User Function Library (UFLs) that provides emailing functionality.
At least one of the 3rd-party UFLs listed here provide such functionality.
Similar Messages
-
Color report rows based on a value in that row
I would like to Color report rows based on a value in that row.
For examplle with the "EMP" table:
I would like job=MANAGER to be red and job=CLERK to be green etc etc
The other example I found only had the option of one color either the highlight or the default color.
I am looking for a way to do multiple colors.Hi,
In the row template, you can use #1#, #2#, etc to indicate where a field in the report needs to be output. This does not have to be plain text - ie, you can use it within style tags if you like.
So, take a query like:
SELECT EMPNO,
ENAME,
DEPTNO,
DECODE(DEPTNO, 10, 'green', 20, 'red', 30, 'cyan', 'white') BG_COLOUR
FROM EMPYou get columns 1=empno, 2=ename, 3=deptno and 4=bg_colour. In the row template, you can then do:
Before Rows setting (sets up the table):
<table>
<tr><td>ID</td><td>Name</td><td>Dept</td></tr>After Rows setting (closes the table):
</table>Row Template 1 (used for ALL rows):
<tr style="background-color:#4#;"><td>#1#</td><td>#2#</td><td>#3#</td></tr>Then, for every row, the colour that has been calculated using the DECODE function will be used in the style tag to colour the background for the entire row.
How you determine the colours is up to you. I've used DECODE here, but you could use a field on the DEPT table to hold this and use this in your SQL statement.
Andy -
Attribute value of previous row
Hi
I have a read only VO.
I need attribute value of previous row .
how can i get it ?
consider these 3 attributes and their values :
Id ** add ** sum
1 *** 10 *** 10 -- > (value of previous sum + new value of add)
2 *** 20 *** 10 + 20 = 30 -- > (value of previous sum + new value of add)
3 *** 30 *** 30 + 30 = 60 -- > (value of previous sum + new value of add)
now , i write a method in impl and call this method in page def by invoke action .
i used Row[] rows = this.getViewObject().getAllRowsInRange(); in my method.
but i am looking for better solution.Hi,
If you wanted to do a running total like that, you could certainly use analytics to do that in the SQL statement itself (provided you're using an Oracle database). use SUM() over ()...
John -
Sum of Values from previous rows in a dynamic table
Hello,
I have a dynamic table has multiple rows (added dynamically via a button). One column in the table is a Quantity column. Another is a Total column. We do not want to keep a running total, but only wish to display a total when the rest of the cells in that row are emty and the previous row(s) has/have values in the Quantity column. The Total is the sum on the Quatnities up to a blank row. Below is a sample. How do I get teh value of the Quantities in the previous rows?
Quantity
Total
5
8
12
25
7
27
34
22
22
Another option might be to put the Total in the last row with data as opposed to the row below the data.
Any ideas?
Regards,
KarlThe script is written to achive your requirement (i.e. the second approach you have mentioned)
You can either contact me at [email protected] to get the sample form created.
Or the following is the XML Source of the form. Copy the entire content in XML source view of your form and see the result.
<?xml version="1.0" encoding="UTF-8"?>
<?xfa generator="AdobeLiveCycleDesignerES_V9.0.0.0.20091029.1.612548" APIVersion="3.1.9277.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/" timeStamp="2012-02-28T14:04:54Z" uuid="2c561cdf-3377-4e84-9a89-51e740bb2fea">
<template xmlns="http://www.xfa.org/schema/xfa-template/2.8/">
<?formServer defaultPDFRenderFormat acrobat9.0dynamic?>
<subform name="form1" layout="tb" locale="en_US" restoreState="auto">
<pageSet>
<pageArea name="Page1" id="Page1">
<contentArea x="0.25in" y="0.25in" w="197.3mm" h="284.3mm"/>
<medium stock="a4" short="210mm" long="297mm"/>
<?templateDesigner expand 1?></pageArea>
<?templateDesigner expand 1?></pageSet>
<subform w="197.3mm" layout="tb">
<subform name="Subform1" w="190.5mm" h="25.4mm">
<field name="Button1" y="15.875mm" x="60.325mm" w="28.575mm" h="6mm">
<ui>
<button highlight="inverted"/>
</ui>
<font typeface="Myriad Pro"/>
<caption>
<value>
<text>Add Row</text>
</value>
<para vAlign="middle" hAlign="center"/>
</caption>
<border hand="right">
<?templateDesigner StyleID apbx2?>
<edge stroke="raised"/>
<fill/>
</border>
<bind match="none"/>
<event activity="click" name="event__click">
<script contentType="application/x-javascript">
try
Subform2.Table1._Row1.addInstance(1);
//for(var i=0;i<Subform2.Table1._Row1.count;i++)
//xfa.resolveNode("Subform2.Table1.Row1["+i+"].Total").execEvent("exit");
}catch(e)
app.alert(e)
</script>
</event>
</field>
<?templateDesigner expand 1?></subform>
<subform name="Subform2" w="196.85mm">
<subform name="Table1" layout="table" columnWidths="55.916mm 44.47mm" x="38.1mm" y="12.7mm">
<border>
<edge/>
</border>
<subform layout="row" name="HeaderRow" id="HeaderRow_ID">
<assist role="TH"/>
<draw h="10mm" name="Cell1">
<border>
<edge/>
<corner thickness="0.1778mm"/>
</border>
<ui>
<textEdit/>
</ui>
<value>
<text>Quantity</text>
</value>
<font typeface="Myriad Pro"/>
<margin topInset="0.5mm" bottomInset="0.5mm" leftInset="0.5mm" rightInset="0.5mm"/>
<para vAlign="middle" hAlign="center"/>
</draw>
<draw h="10mm" name="Cell2">
<border>
<edge/>
<corner thickness="0.1778mm"/>
</border>
<ui>
<textEdit/>
</ui>
<value>
<text>Total</text>
</value>
<font typeface="Myriad Pro"/>
<margin topInset="0.5mm" bottomInset="0.5mm" leftInset="0.5mm" rightInset="0.5mm"/>
<para vAlign="middle" hAlign="center"/>
</draw>
<border>
<edge presence="hidden"/>
</border>
<occur max="-1"/>
<?templateDesigner expand 1?></subform>
<subform layout="row" name="Row1">
<assist role="TR"/>
<field name="Quantity" w="55.916mm" h="9.317mm">
<ui>
<numericEdit>
<border presence="hidden">
<?templateDesigner StyleID aped0?></border>
<margin/>
</numericEdit>
</ui
><
font typeface="Myriad Pro"/><
margin topInset="1mm" bottomInset="1mm" leftInset="1mm" rightInset="1mm"/><
para vAlign="middle"/><
border><
edge/><
corner thickness="0.1778mm"/></
border></
field><
field name="Total" w="44.47mm" h="9.317mm" access="readOnly"><
ui><
numericEdit><
border presence="hidden">
<?templateDesigner StyleID aped0?>
</border><
margin/></
numericEdit></
ui><
font typeface="Myriad Pro"/><
margin topInset="1mm" bottomInset="1mm" leftInset="1mm" rightInset="1mm"/><para vAlign="middle"/>
<border>
<edge/>
<corner thickness="0.1778mm"/>
</border>
<calculate>
<script contentType="application/x-javascript">
try
var nextRow = xfa.resolveNode("Subform2.Table1.Row1["+(this.parent.instanceIndex+1)+"]"); // Next row of the table
if((nextRow==null || nextRow.Quantity.rawValue == null || nextRow.Quantity.rawValue=="") && Quantity.rawValue!=null) // If there is no more rows OR the next row don't contain any Quantity value
var subTotal = 0;
for(var j=this.parent.instanceIndex;j>=0;j--) // Loop until the previous row has empty value OR reach start of row Index (i.e. 0)
var prevObj = xfa.resolveNode("Subform2.Table1.Row1["+j+"].Quantity"); // locate the previous row's Quantity object
if(prevObj.rawValue == null || prevObj.rawValue=="")
break; // if blank value found, skip the loop
subTotal+= prevObj.rawValue;
this.rawValue = subTotal; // Update the Total value
}else
this.rawValue = null; // Clear the total value
}catch(e)
app.alert(e)
</script>
</calculate>
</field>
<border>
<edge presence="hidden"/>
</border>
<occur max="-1"/>
<?templateDesigner expand 1?></subform>
<keep intact="contentArea"/>
<?templateDesigner rowpattern first:1, next:1, firstcolor:f0f0f0, nextcolor:ffffff, apply:0?>
<overflow leader="HeaderRow"/>
<?templateDesigner expand 1?></subform>
<?templateDesigner expand 1?></subform>
<?templateDesigner expand 1?></subform>
<proto/>
<desc>
<text name="version">9.0.0.0.20091029.1.612548.606130</text>
</desc>
<?templateDesigner expand 1?></subform>
<?templateDesigner DefaultPreviewDynamic 1?>
<?templateDesigner DefaultRunAt client?>
<?templateDesigner Grid show:1, snap:1, units:0, color:ff8080, origin:(0,0), interval:(125000,125000)?>
<?templateDesigner FormTargetVersion 28?>
<?templateDesigner DefaultLanguage JavaScript?>
<?acrobat JavaScript strictScoping?>
<?templateDesigner Zoom 62?>
<?templateDesigner Rulers horizontal:1, vertical:1, guidelines:1, crosshairs:0?>
<?templateDesigner SaveTaggedPDF 1?>
<?templateDesigner SavePDFWithEmbeddedFonts 1?></template>
<config xmlns="http://www.xfa.org/schema/xci/2.8/">
<agent name="designer">
<!-- [0..n] -->
<destination>pdf</destination>
<pdf>
<!-- [0..n] -->
<fontInfo/>
</pdf>
</agent>
<present>
<!-- [0..n] -->
<pdf>
<!-- [0..n] -->
<fontInfo/>
<version>1.7</version>
<adobeExtensionLevel>3</adobeExtensionLevel>
</pdf>
<xdp>
<packets>*</packets>
</xdp>
</present>
</config>
<localeSet xmlns="http://www.xfa.org/schema/xfa-locale-set/2.7/">
<locale name="en_US" desc="English (United States)">
<calendarSymbols name="gregorian">
<monthNames>
<month>January</month>
<month>February</month>
<month>March</month>
<month>April</month>
<month>May</month>
<month>June</month>
<month>July</month>
<month>August</month>
<month>September</month>
<month>October</month>
<month>November</month>
<month>December</month>
</monthNames>
<monthNames abbr="1">
<month>Jan</month>
<month>Feb</month>
<month>Mar</month>
<month>Apr</month>
<month>May</month>
<month>Jun</month>
<month>Jul</month>
<month>Aug</month>
<month>Sep</month>
<month>Oct</month>
<month>Nov</month>
<month>Dec</month>
</monthNames>
<dayNames>
<day>Sunday</day>
<day>Monday</day>
<day>Tuesday</day>
<day>Wednesday</day>
<day>Thursday</day>
<day>Friday</day>
<day>Saturday</day>
</dayNames>
<dayNames abbr="1">
<day>Sun</day>
<day>Mon</day>
<day>Tue</day>
<day>Wed</day>
<day>Thu</day>
<day>Fri</day>
<day>Sat</day>
</dayNames>
<meridiemNames>
<meridiem>AM</meridiem>
<meridiem>PM</meridiem>
</meridiemNames>
<eraNames>
<era>BC</era>
<era>AD</era>
</eraNames>
</calendarSymbols>
<datePatterns>
<datePattern name="full">EEEE, MMMM D, YYYY</datePattern>
<datePattern name="long">MMMM D, YYYY</datePattern>
<datePattern name="med">MMM D, YYYY</datePattern>
<datePattern name="short">M/D/YY</datePattern>
</datePatterns>
<timePatterns>
<timePattern name="full">h:MM:SS A Z</timePattern>
<timePattern name="long">h:MM:SS A Z</timePattern>
<timePattern name="med">h:MM:SS A</timePattern>
<timePattern name="short">h:MM A</timePattern>
</timePatterns>
<dateTimeSymbols>GyMdkHmsSEDFwWahKzZ</dateTimeSymbols>
<numberPatterns>
<numberPattern name="numeric">z,zz9.zzz</numberPattern>
<numberPattern name="currency">$z,zz9.99|($z,zz9.99)</numberPattern>
<numberPattern name="percent">z,zz9%</numberPattern>
</numberPatterns>
<numberSymbols>
<numberSymbol name="decimal">.</numberSymbol>
<numberSymbol name="grouping">,</numberSymbol>
<numberSymbol name="percent">%</numberSymbol>
<numberSymbol name="minus">-</numberSymbol>
<numberSymbol name="zero">0</numberSymbol>
</numberSymbols>
<currencySymbols>
<currencySymbol name="symbol">$</currencySymbol>
<currencySymbol name="isoname">USD</currencySymbol>
<currencySymbol name="decimal">.</currencySymbol>
</currencySymbols>
<typefaces>
<typeface name="Myriad Pro"/>
<typeface name="Minion Pro"/>
<typeface name="Courier Std"/>
<typeface name="Adobe Pi Std"/>
<typeface name="Adobe Hebrew"/>
<typeface name="Adobe Arabic"/>
<typeface name="Adobe Thai"/>
<typeface name="Kozuka Gothic Pro-VI M"/>
<typeface name="Kozuka Mincho Pro-VI R"/>
<typeface name="Adobe Ming Std L"/>
<typeface name="Adobe Song Std L"/>
<typeface name="Adobe Myungjo Std M"/>
</typefaces>
</locale>
</localeSet>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.2.1-c043 52.398682, 2009/08/10-13:00:47 ">
<
rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><
rdf:Description xmlns:xmp="http://ns.adobe.com/xap/1.0/" rdf:about=""><
xmp:MetadataDate>2012-02-28T14:04:54Z</xmp:MetadataDate><
xmp:CreatorTool>Adobe LiveCycle Designer ES 9.0</xmp:CreatorTool></
rdf:Description><
rdf:Description xmlns:pdf="http://ns.adobe.com/pdf/1.3/" rdf:about=""><
pdf:Producer>Adobe LiveCycle Designer ES 9.0</pdf:Producer></
rdf:Description><
rdf:Description xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" rdf:about=""><
xmpMM:DocumentID>uuid:2c561cdf-3377-4e84-9a89-51e740bb2fea</xmpMM:DocumentID></
rdf:Description><
rdf:Description xmlns:desc="http://ns.adobe.com/xfa/promoted-desc/" rdf:about=""><
desc:version rdf:parseType="Resource"><
rdf:value>9.0.0.0.20091029.1.612548.606130</rdf:value><
desc:ref>/template/subform[1]</desc:ref></
desc:version></
rdf:Description></
rdf:RDF></
x:xmpmeta></xdp:xdp> -
I have a SSRS report which uses a matrix for a crosstab effect.
Each row contains about 10 score values in 10 columns respectively. I need each row to check against the previous row, and i need each score value in each column to be compared to the corresponding column score value in the previous row.
If the current score is greater than the corresponding previous score (in the previous row), then i want to change the background of the cell.
if the current score is smaller than the previous, then it's a different color.
if they are equal, or it's the first row in the matrix table, then leave white.
I have found custom code functions to use in the SSRS expression fields, but every single one of them compares against the previous COLUMN value and not the previous ROW value which is what i need. the "Previous" function would be perfect if i
could use it in a matrix but i can't. (i keep getting error "The use of a Previous aggregate function in a tablix cell is not supported"). looking around it turns out that matrices are arrange in groups and not in rows which is why Previous can't
be used and the only way is with custom code.
Please help. if you have any custom code samples that achieve what i need, please share, or give me advice on how to achieve this.
Thank youI figured it out. Maybe it can help someone else in the future:
Public Shared count as Integer = 0
Public Shared currentRow As Integer = 1
Public Shared MatrixStructures As New System.Collections.Generic.List(Of MatrixStructure)()
Public Shared Function GetCellColor(row as Integer, score as Integer)
If (row > currentRow) Then
count = 0
currentRow = row
End If
count = count + 1
Dim matrixStructure As New MatrixStructure()
matrixStructure.RowIndex = row
matrixStructure.ColumnIndex = count
matrixStructure.ScoreValue = score
MatrixStructures.Add(matrixStructure)
If score = 0 Then
Return "White"
End If
Dim val As MatrixStructure = MatrixStructures.Find(Function(s As MatrixStructure)
Return s.GetRowIndex() = row - 1 AndAlso s.GetColumnIndex() = count
End Function)
If (Not (val Is Nothing)) Then
If val.scoreValue = 0 Then
Return "White"
End If
If score >= val.scoreValue + 2 Then
Return "Green"
ElseIf score <= val.scoreValue - 2 Then
Return "Red"
End If
End If
Return "White"
End Function
Public Class MatrixStructure
Public rowIndex As Integer
Property GetRowIndex() As Integer
Get
Return rowIndex
End Get
Set(ByVal Value As Integer)
rowIndex = Value
End Set
End Property
Public columnIndex As Integer
Property GetColumnIndex() As Integer
Get
Return columnIndex
End Get
Set(ByVal Value As Integer)
columnIndex = Value
End Set
End Property
Public scoreValue As Integer
Property GetScoreValue () As Integer
Get
Return scoreValue
End Get
Set(ByVal Value As Integer)
scoreValue = Value
End Set
End Property
End Class
and to pass the current row number from the expression i use this
Ceiling(RowNumber(NOTHING) / 10)
i divide the row number by 10 because there are ten columns. if you don't know the number of columns, or it's a variable number, then return it from the stored procedure query in the first place. that's what I had to do -
SQL Developer - Pulling column value from previous row
I am using Oracle SQL developer and trying to pull a value from a column from the previous row.
Currently this is an example from the code im using.
Select CD1.nbr_dw, CD1.SEQ_DW, CD1.CDL_NET_PAID, CD1.UNITS_ALLOW,CD1.ALLOW_AMT, CD1.UNIT_PRICE, CD1.BACKED_OUT,
case
When CD1.NET_PAID = 0 then 0
****NEW CODE*****
Else CD1.ALLOW_AMT / CD1.UNIT_PRICE
end as NEW_UNITS
From Table_A CD1
join (Select nbr_dw, DET_DW, SEQ_DW
From Table_B
) CD2
on CD1.nbr_dw = CD2.nbr_dw
I need to add another when statement that says when CD1.BACKED_OUT = 'Y' populated the NEW_UNITS field with the previous rows value of CD1.UNIT_PRICE. Note, the CD1.SEQ_DW can be used to determine the previous row. Any ideas?Hi,
Welcome to the forum!
The analytic LAG function can return a value from the previous row:
LAG (cd1.unit_price) OVER ( -- PARTITION BY x -- if needed
ORDER BY cd1.seq_dw
)It's unclear if you need a PARTITION BY clause or not.
"PARTITION BY x" means that you want the value from the last row that has the same value of x as the current row.
If you omit the PARTITION BY clause, it means you want the last row regardless of what any other columns are.
Whenever you have a problem, it ehlps if you post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
Explain how you get those results from that data.
Always say what version of Oracle you're using. -
Update field taking value from previous row
I have a table TEST (ID int, name varchar(20), amount decimal(18,0)).
First row of the table have correct value. I want to update amount column except first row by adding 10 with the previous row value without using cursor.
id Name Amount
1 abc 10
2 def 15
3 ghi 20
4 jkl 22
5 mno 25
6 pqr 27
7 stu 30
8 vwx 33
id Name Amount
1 abc 10
2 def 20
3 ghi 30
4 jkl 40
5 mno 50
6 pqr 60
7 stu 70
8 vwx 80
please help me.
thanks
srimanta mannacreate table #t (id int, amount int)
insert into #t values (1,10)
insert into #t values (2,25)
insert into #t values (3,46)
insert into #t values (4,55)
insert into #t values (5,160)
insert into #t values (6,89)
insert into #t values (7,100)
with cte
as
select *,(select min(amount) from #t t where t.id=1) as a
FROM #t
) update #t set amount=(select sum(a) from cte c where c.id<=cte.id)
from cte where #t.id=cte.id
select * from #t
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Expanding table: Calculating difference to value from previous row
Hi there,
I am a complete newbie to LiveCycle Designer (ES2) and have created below document with an expanding table.
Shared Files - Acrobat.com
My aim is to make the form user friendly by adding a calculation in the field "Twist" which calculates the difference from the current row to the previous row.
I have no idea about Java Script, I am afraid, and also don't know if this is possible at all so it's probably a bad idea after all.
The reason for setting it up as an expanding table is so that the form can be used for all 32 instances the form would be used for (they would all require different amount of rows altogether).
The calculation would start in row 2 (Checklist.Table1), take the twist value entered in row 2 and calculate the difference to the twist value entered in row 1.
Then in row 3, it would calculate the difference between twist value in row 3 to row 2 etc.
So subtract value of field in rown with value in rown-1 or something in this direction.
Is there anyone at all who could help me with this at all?
I'd be very grateful for any advice you could give me.
Thanks a lot!
MathildaNot sure what happened with the formatting there, try this;
if (Row1.index > 0 && !Row1.resolveNode("NumericField4[0]").isNull)
var prevTwist = Table1.resolveNode("Row1[" + (Row1.index - 1) + "].NumericField4[0]").rawValue
var result = Math.abs(3000 / (Row1.resolveNode("NumericField4[0]").rawValue - prevTwist));
this.rawValue = result;
else
this.rawValue = ""; -
Getting previous value from previous row
Hi,
My desired output should be
ID Book_date Credit Previous_Credit
123IT1 12/8/2008 100800 72500
from this table:
ID Book date Credit
123IT1 12/8/2008 100800
123IT1 12/18/2007 72500
123IT1 11/14/2006 150720
I tried to use the lead function but I'm having problem when I included the date range condtion:
This is my query:
select id, book_date, credit, lead(credit) over (order by rownum) as previous_credit
from t
where book_date between '01-December-2008' and '31-December-2008'
Result
ID Book_date Credit Previous_Credit
123IT1 12/8/2008 100800
The previous_credit column is always blank. I think because of the date range..?
Any idea how to get the right result? pls. helpYour expected output indicates that you may require a LAG
SQL> with t as
2 (
3 select '123IT1' id, to_date('12/08/2008','mm/dd/yyyy') Book_Date, 100800 Credit from dual uni
on
4 select '123IT1', to_date('12/18/2007','mm/dd/yyyy'), 72500 from dual union
5 select '123IT1', to_date('11/14/2006','mm/dd/yyyy'), 150720 from dual
6 )
7 --
8 select id
9 ,Book_Date
10 ,Credit
11 ,lag(Credit) over (partition by id order by Book_Date) Previous_Credit
12 from t
13 /
ID BOOK_DATE CREDIT PREVIOUS_CREDIT
123IT1 14-NOV-06 150720
123IT1 18-DEC-07 72500 150720
123IT1 08-DEC-08 100800 72500If you always require a Previous Credit then you may want to modify this:
(partition by id order by Book_Date)to this:
(order by id, Book_Date) -
Dont show fields with same value as previous row.
Hi, If I have a table like this:
DEPNO_MONTH__COST__ID
10_____ Jan______100___ 2
10_____ Jan______200___ 4
10_____ Jan_______50____3
20_____ Feb______30____4
30_____ Jan ______30____5
30_____ Feb______40____6
I need a select that shows the table like this:
DEPNO_MONTH_COST_ID
10______Jan_____100___2
________________200___4
________________50____3
20______Feb_____30____4
30______Jan_____30____5
________Feb_____40____6
Can someone please help me? (ingore underscore)
/Sörenlike this ?
SQL> select decode(rno1, 1, depno, null) depno,
2 decode(rno2, 1, mon, null) month,
3 cost, id
4 from (select depno,
5 mon,
6 row_number() over (partition by depno order by depno, mon, cost ) rno1,
7 row_number() over (partition by depno, mon order by depno, mon, cost ) rno2,
8 cost, id
9 from t1
10 order by depno, mon, cost );
DEPNO MONTH COST ID
10 Jan 50 3
100 2
200 4
20 Feb 30 4
30 Feb 40 6
Jan 30 5
6 rows selected.
SQL>
[pre] -
? Tsql query to add a sumTotal column from value in current row + value in previous row
--using Sql Server 2008 (Developer)
create table #tmp1(rowID int Identity(1,1), val1 int)
insert into #tmp1(val1)
select 5 union all
select 8 union all
select 12 union all
select 13 union all
select 22 union all
select -7 union all
select 25 union all
select 19 union all
select 32 union all
select -17
What Tsql could produce a result set as follows based on the data from #tmp1?
rowID val1 sumTotal
1 5 5
2 8 13
3 12 25
4 13 37
5 22 59
6 -7 52
7 25 77
8 19 96
9 32 128
10 -17 111
Rich PIn SQL 2008 check these links
http://social.technet.microsoft.com/wiki/contents/articles/19670.t-sql-useful-links.aspx#Running_Total
In SQL 2012 and up, the Running total can be calculated directly with ordered SUM
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
Analytical function need to work based on previous rows result.
My data are sorted based on sartdatetime column.but i need the sum(value) based on below condition.
Condition :
i need to check with current row with previous rows
if they are same then i need to sum the value with previous row.
else i need to start the summation.
My data like below:
Rownum Code Sartdatetime Value
1 4619 12/9/2012 11:00 219
2 5344 12/9/2012 14:39 27
3 4619 12/9/2012 15:11 20
4 4619 12/9/2012 19:33 14
5 4619 12/9/2012 20:53 16
6 6851 12/9/2012 21:21 1
7 4619 12/9/2012 21:22 35
8 5623 12/10/2012 1:59 4
9 5623 12/10/2012 2:03 3
10 5623 12/10/2012 2:06 5
11 4619 12/10/2012 2:17 1
12 5623 12/10/2012 2:18 5
13 5623 12/10/2012 2:25 2
14 5623 12/10/2012 2:27 2
15 4619 12/10/2012 2:29 30
Eg:
Take the first row. For that no previous rows. So we directly added the value like below.
Rownum Code Sartdatetime Value sum(val)
1 4619 12/9/2012 11:00 219 219
take the seconds row, we can check the code value (5344)with first row value (4619). the values are different . So our summation like.
2 5344 12/9/2012 14:39 27 27
for third row , we can check the code value (4619)with second row value (5344). the values are different . So our summation like.
3 4619 12/9/2012 15:11 20 20
for fourth row we can check the code value (4619)with second row value (4619). the values are same. So our summation like.
4 4619 12/9/2012 19:33 14 34 - The sum of previous row result.
5 th row also same value so
5 4619 12/9/2012 20:53 16 50T he sum of previous row result.
then the same value come again in 7 th row so here we need to start the summation like below.
7 4619 12/9/2012 21:22 35 35.
i want the result like below.
Rownum Code Sartdate time Value Expected result
1 4619 12/9/2012 11:00 219 219
2 5344 12/9/2012 14:39 27 27
3 4619 12/9/2012 15:11 20 20
4 4619 12/9/2012 19:33 14 34
5 4619 12/9/2012 20:53 16 50
6 6851 12/9/2012 21:21 1 1
7 4619 12/9/2012 21:22 35 35
8 5623 12/10/2012 1:59 4 4
9 5623 12/10/2012 2:03 3 7
10 5623 12/10/2012 2:06 5 12
11 4619 12/10/2012 2:17 1 1
12 5623 12/10/2012 2:18 5 5
13 5623 12/10/2012 2:25 2 7
14 5623 12/10/2012 2:27 2 9
15 4619 12/10/2012 2:29 30 30
Please helpHi,
Welcome to the forum!
Here's one way to do what you want:
WITH got_grp_id AS
SELECT code, starttime, value
, ROW_NUMBER () OVER ( ORDER BY starttime ) AS r_num
, ROW_NUMBER () OVER ( ORDER BY starttime )
- ROW_NUMBER () OVER ( PARTITION BY code
ORDER BY starttime
) AS grp_id
FROM table_x
SELECT r_num
, code
, starttime
, value
, SUM (value) OVER ( PARTITION BY code, grp_id
ORDER BY starttime
) AS sum_value
FROM got_grp_id
ORDER BY starttime
;For an explanation of the Fixed Difference technique, see {message:id=9953384} and/or {message:id=9957164}
Whenever you have a problem, please post CREATE TABLE and INSERT statements for your same data. For example:
CREATE TABLE table_x
( code NUMBER (4)
, starttime DATE UNIQUE
, value NUMBER
INSERT INTO table_x (code, starttime, value)
VALUES (4619, TO_DATE ( '12/9/2012 11:00', 'MM/DD/YYYY HH24:MI'),
219);
INSERT INTO table_x (code, starttime, value)
VALUES (5344, TO_DATE ( '12/9/2012 14:39', 'MM/DD/YYYY HH24:MI'),
27);
INSERT INTO table_x (code, starttime, value)
VALUES (4619, TO_DATE ( '12/9/2012 15:11', 'MM/DD/YYYY HH24:MI'),
20);
INSERT INTO table_x (code, starttime, value)
VALUES (4619, TO_DATE ( '12/9/2012 19:33', 'MM/DD/YYYY HH24:MI'),
14);
INSERT INTO table_x (code, starttime, value)
VALUES (4619, TO_DATE ( '12/9/2012 20:53', 'MM/DD/YYYY HH24:MI'),
16);
INSERT INTO table_x (code, starttime, value)
VALUES (6851, TO_DATE ( '12/9/2012 21:21', 'MM/DD/YYYY HH24:MI'),
1);
INSERT INTO table_x (code, starttime, value)
VALUES (4619, TO_DATE ( '12/9/2012 21:22', 'MM/DD/YYYY HH24:MI'),
35);
INSERT INTO table_x (code, starttime, value)
VALUES (5623, TO_DATE ( '12/10/2012 1:59', 'MM/DD/YYYY HH24:MI'),
4);
INSERT INTO table_x (code, starttime, value)
VALUES (5623, TO_DATE ('12/10/2012 2:03' , 'MM/DD/YYYY HH24:MI' ),
3);
INSERT INTO table_x (code, starttime, value)
VALUES (5623, TO_DATE ( '12/10/2012 2:06', 'MM/DD/YYYY HH24:MI'),
5);
INSERT INTO table_x (code, starttime, value)
VALUES (4619, TO_DATE ( '12/10/2012 2:17', 'MM/DD/YYYY HH24:MI'),
1);
INSERT INTO table_x (code, starttime, value)
VALUES (5623, TO_DATE ( '12/10/2012 2:18', 'MM/DD/YYYY HH24:MI'),
5);
INSERT INTO table_x (code, starttime, value)
VALUES (5623, TO_DATE ( '12/10/2012 2:25', 'MM/DD/YYYY HH24:MI'),
2);
INSERT INTO table_x (code, starttime, value)
VALUES (5623, TO_DATE ('12/10/2012 2:27' , 'MM/DD/YYYY HH24:MI' ),
2);
INSERT INTO table_x (code, starttime, value)
VALUES (4619, TO_DATE ( '12/10/2012 2:29', 'MM/DD/YYYY HH24:MI'),
30);
COMMIT; See the forum FAQ {message:id=9360002}
Output:
R_NUM CODE STARTTIME VALUE SUM_VALUE
1 4619 12/9/2012 11:00 219 219
2 5344 12/9/2012 14:39 27 27
3 4619 12/9/2012 15:11 20 20
4 4619 12/9/2012 19:33 14 34
5 4619 12/9/2012 20:53 16 50
6 6851 12/9/2012 21:21 1 1
7 4619 12/9/2012 21:22 35 35
8 5623 12/10/2012 01:59 4 4
9 5623 12/10/2012 02:03 3 7
10 5623 12/10/2012 02:06 5 12
11 4619 12/10/2012 02:17 1 1
12 5623 12/10/2012 02:18 5 5
13 5623 12/10/2012 02:25 2 7
14 5623 12/10/2012 02:27 2 9
15 4619 12/10/2012 02:29 30 30Edited by: Frank Kulash on Dec 24, 2012 6:44 AM
Added sample data. -
Finding all rows based on previous rows column value diffrence
I have an interesting requirement. There is a DATE column and a user in a table and I have to find all rows for all the user for which the previous row and current row has time difference of lets say more than 30 minutes. Rows are already sorted by time.
For example in the following table, we need ID 4 and 6 for user 1.
ID User date
1 1 today 1 hour 0 min 0 s
2 1 today 1 hour 1 min 0 s
3 1 today 1 hour 29 min 0 s
*4 1 today 1 hour 59 min 3 s*
5 1 today 2 hour 10 min 2 s
*6 1 today 2 hour 50 min 7 s*
Edited by: user733179 on Mar 5, 2009 12:00 PMHi,
To get all the users in the result set, outer-join to a table (or subquery, as shown bleow) that has one row per user:
WITH got_dif AS
SELECT id, dt, usr
, (dt - LAG (dt)
OVER ( PARTITION BY usr
ORDER BY dt
) -- difference in days
* 24 * 60 AS minutes_dif
FROM table_x
-- WHERE ... -- if needed
, all_users AS
SELECT DISTINCT usr
FROM table_x
SELECT gd.id, gd.dt, au.usr
, NVL2 ( gd.usr
, 'Okay'
, 'Dif is never > 30'
) AS flag
FROM all_users
LEFT OUTER JOIN got_dif ON gd.usr = au.usr
AND gd.minutes_dif > 30
;Notice that the test for a 30-minute difference is part of the join condition.
You don't need the flag column, and you may not want it.
If you would prefer a separate query of just the users that are not in the original result set, then you can use the original query (modified only slightly) as an EXISTS ior NOT IN sub-query. For example:
SELECT DISTINCT usr
FROM table_x
WHERE usr NOT IN
WITH got_dif AS
SELECT id, dt, usr
, (dt - LAG (dt)
OVER ( PARTITION BY usr
ORDER BY dt
) -- difference in days
* 24 * 60 AS minutes_dif
FROM table_x
-- WHERE ... -- if needed
SELECT usr -- Only 1 column in SELECT clause
FROM got_dif
WHERE minutes_dif > 30
; -
How to get the value of column from previous row to current row?
Hi All,
I am facing a critical problem in SQL query (for reporting purpose (COGNOS)). please reply to my query.
REQUIREMENT: i want to retrive value of a column (this is not a table column, this will be calculated based expression) from previous row to current row.
EXAMPLE:
TABLE NAME: i have to join multiple tables. so, i am not mentioning table names here.
DISPLAY COLUMNS in the report: item, loc, sku, beginval (not table column), endval (not table column, this will calculated based on some expressions), etc. Here, first time the value of BEGINVAL will be taken from some x column name of x table. ENDVAL will calculated based on the expression. For the next row onwards, BEGINVAL will become the value of ENDVAL and the value of ENDVAL will be calculated based on the expression and this expression uses the value of BEGINVAL.
my report will look like below.
ITEM LOC SKU BEGINVAL ENDVAL
1 HYD 1-HYD 10 10+1+2 (13)
2 HYD 2-HYD 13 13+1+2 (16)
3 SEC 3-SEC 16 16+1+2 (19)
4 SEC 4-SEC 19 19+1+2 (22)
etc....
in the above output, BEGINVAL and ENDVAL columns are not part of any table. they are alias column names.if you observe intially BEGINVAL will be assigned to some value, but from subsequent rows, BEGINVAL will become the ENDVAL of previous row.
Please help me on how to write this query?Hi, please find the detail description of the problom.
DDL (table scripts)
ITEM
CREATE TABLE ITEM
ITEM VARCHAR2(50 CHAR) NOT NULL,
DESCR VARCHAR2(50 CHAR) DEFAULT ' ' NOT NULL,
UOM VARCHAR2(50 CHAR)
SKU
CREATE TABLE SKU
ITEM VARCHAR2(50 CHAR) NOT NULL,
LOC VARCHAR2(50 CHAR) NOT NULL,
OH float
SKUPROJSTATIC
CREATE TABLE SKUPROJSTATIC
ITEM VARCHAR2(50 CHAR) NOT NULL,
LOC VARCHAR2(50 CHAR) NOT NULL,
STARTDATE DATE
VehicleLoad
CREATE TABLE VEHICLELOAD
LOADID VARCHAR2(50 CHAR) NOT NULL,
DESCR VARCHAR2(50 CHAR) DEFAULT ' ' NOT NULL,
SHIPDATE DATE DEFAULT TO_DATE('01/01/1970','MM/DD/YYYY') NOT NULL,
ARRIVDATE DATE
VEHICLELOADLINE
CREATE TABLE VEHICLELOADLINE
LOADID VARCHAR2(50 CHAR) NOT NULL,
ITEM VARCHAR2(50 CHAR) NOT NULL,
QTY float(126)
DML scripts
I can't provide the the DML scripts, because its very huge data.
Main QUERY is below.
below is the query which i have to write and execute.
select
i.item,
i.descr,
i.unitsperpallet,
sp.loc,
sp.startdate,
'Crucial_IND',
LAG (EndBal,1,0) OVER (ORDER BY STARTDATE) BeginBal,
SP.FCSTCUSTORDERS CustOrders,
SP.COMMITINTRANSOUT,
SP.RECARRIV,
SP.TOTINTRANSIN,
(BeginBal - sp.FCSTCUSTORDERS - sp.COMMITINTRANSOUT + sp.TOTINTRANSIN ) EndBal,
'CuttingQty',
VLL.QTY,
vl.source,
vl.arrivdate,
vl.shipdate,
vl.loadid,
s.oh
from item i, skuprojstatic sp, sku s, VehicleLoad vl, VehicleLoadLine vll
where sp.item = i.item
and s.item=i.item
and sp.item =s.item (+)
and sp.loc = s.loc (+)
and vll.item = s.item
and vll.loadid = vl.loadid
and to_char(sp.startdate ,'mm/dd/yyyy') = to_char(vl.arrivdate,'mm/dd/yyyy')
and sp.loc = vl.dest (+)
order by sp.startdate
problem description: in the above query, BeginBal and EndBal is what i am looking for. when i execute this query, oracle throwing an error saying that alias names can't be used as expressions. For the first row, the BeginBal should be the value sku.OH and for the subsequent rows, this value will be the previous row value of EndBal. -
How to propogate previous row value
All,
I have a query were I need to fill the null data with previous row value. Like I have a table were we record all the On hand quantity for a item for a date. Lets say I have only 2 rows in this table for a month then I am planning to write a view that will give me 31/30 rows for a month and if for a specific date is the value is null then it should read from previous row unitl it finds the data otherwise display 0.
Ex. Actual table
Item No Date Qty
1 1/1/2010 10
1 1/5/2010 15
View I have written, I need to fill the null Qty with previous row data
Item No Date Qty
1 1/1/2010 10
1 1/2/2010
1 1/3/2010
1 1/4/2010
1 1/5/2010 15
1 1/6/2010
I want something like this how can i do this?
Item No Date Qty
1 1/1/2010 10
1 1/2/2010 10
1 1/3/2010 10
1 1/4/2010 10
1 1/5/2010 15
1 1/6/2010 15
ThanksHi Sung, sorry by my delay
Basically I'm building a Client Framework that a lot of actions are automatically managed, then I extend Objects
for example EntityImpl. I let to user set any value to the
database mapped fields but I will check this values
using my own bussines rules before to insert into database
and if this values are wrong I display an alert.
My problem is that I catch insert event to call validate
functions. But when any value is wrong I will show an alert, but if user commits transaction after validate
funcion is not revalidated. Well I supose that is a bad implementation for validation rules, now amb reading about
Validationlistener because I think is the best way to do
all that I need. I let to the user add field values but
these values not will commited while validationListeners
return isValid = true;
Thanks Sung.
Albert.
Maybe you are looking for
-
How to change The Standard JOptionPane Icon?
in this simple code i want to change the Standard JOptionPane icon to a different icon how could it be? thank you import java.awt.*; import javax.swing.*; import java.awt.event.WindowListener; import java.awt.event.WindowEvent; import javax.sound.sam
-
Check battery temperature if your Z1 isn't charging
If you press *#*#4636#*#* in the dialing screen it'll show you the battery temperature. I think there is a bug which causes the battery temperature to be determined as unusually low. If the temperature is below 4 or 5 degrees Celsius then it won't ch
-
who could help me do it for free i will never forget you
-
Project planing compare with actual situation
Hello all, I have following questions: 1. Is there a possibility to see in the GANTT chart both the projected and real duration of a task/phase, ideally two rectangles for each component - similar to MS Project for example? 2. Is there any possibilit
-
Backing up files in USB External Hardrive
I hope this is an appropriate to place to post: I bought a used SEAGATE Internal Hardrive 160gigs with an enclousure, so it works just like an external hard drive. Now the enclousure is only for USB. I have as of now partioned it into 2, as MAC OX Ex