TSQL Get Previous values for each group by
Dear Friends,
I have a problem with my TSQL statment.
I need to get previous value for each day and specific unit. Everything goes fine if I have always 2 unit in each day. But if same day has just one unit or less, I cannot have the previous value in the current record.
The Output is this one:
SK_DAY SK_UNIT
VALUE VALUE_PREVIUS_DAY
20131112 2
30.00 NULL
20131112 3
34.00 NULL
20131113 2
40.00 30.00
20131113 3
45.00 34.00
20131114 2
50.00 40.00
I dont have the second record for 2013-11-14, because in this date I just have value for unit 2.
The final output should include the record:
20131114 3
0 45.00
The Statment I have is:
SELECT MAIN.SK_DAY, MAIN.SK_UNIT, SUM(MAIN.VALUE) AS VALUE
SELECT SUM(VND1.VALUE) AS VALUE
FROM FCT_TEST VND1
WHERE CONVERT(DATE,CONVERT(VARCHAR(10),VND1.SK_DAY))>=DATEADD(dd,-1,CONVERT(DATE,CONVERT(VARCHAR(10),MAIN.SK_DAY)))
AND CONVERT(DATE,CONVERT(VARCHAR(10),VND1.SK_DAY))<CONVERT(DATE,CONVERT(VARCHAR(10),MAIN.SK_DAY))
AND VND1.SK_UNIT=MAIN.SK_UNIT
) AS VALUE_PREVIUS_DAY
FROM FCT_TEST MAIN
GROUP BY SK_DAY, MAIN.SK_UNIT
SQL CREATE SCRIPT:
CREATE TABLE [dbo].[FCT_TEST](
[SK_DAY] [int] NOT NULL,
[SK_UNIT] [int] NOT NULL,
[VALUE] [decimal](18, 2) NULL,
CONSTRAINT [PK_FCT_TEST] PRIMARY KEY CLUSTERED
[SK_DAY] ASC,
[SK_UNIT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Thank you!!!
PPSQL
Thank you Kalman,
But my problem is not with date! Fortunately I have dates for all days.
The problem is for dimension tables like UNITS that I dont have values for all days, and when I try to get the previous value for previous day and each unit I dont have records.
20131112
2
30.00
NULL
20131112
3
34.00
NULL
20131113
2
40.00
30.00
20131113
3
45.00
34.00
20131114
2
50.00
40.00
20131114
3
0
45.00 [I NEED THIS RECORD AS IS]
Could you help me??
Thank you!!
Similar Messages
-
Query to get possible values for each segment
Hi Gurus,
Give the flex value set id, what is the query to get all possible values for each segment (just like what is shown in the accounting flex window)?
Thank you,
BeibeiHi Beibei,
The table FND_FLEX_VALUES_VL can give you details of values available in the Value set i.e. 1 segment at a time.
If you are looking for a concatenated view of Accounting Flexfield values, that would be available in GL_CODE_COMBINATIONS table.
Regards,
Ivruksha -
Get bit value for each pixel.
i use the 16bit image so i need to get the bit value for each pixel. hope someone knows it can help me. thanks.
Get the BufferedImage Object and do a getData() on it . This returns a Raster object. The Raster Object has methods for retrieving the pixel information.
hope this helps. -
Issue with Report to get Position value for each Class ID.
Hello Experts,
m working on a report where I want Position values as on date.
for an entered date report should give position value(Amount for transaction) for each class Id.
I m trying using the exit variable but could not reach the output.
For date I created an exit variable which shoud return the latest position for each class Id.
Now this exit variable is "ready for Input" . when I debug my code it takes i_step =3 and i_vanm= " " after i_step = 1 and i_vnam = "<variablename>"
how do I go about to get the solution.
Guide me to come up with desired output.
Thanks in Adv.
Bhavna.Hello Experts,
m working on a report where I want Position values as on date.
for an entered date report should give position value(Amount for transaction) for each class Id.
I m trying using the exit variable but could not reach the output.
For date I created an exit variable which shoud return the latest position for each class Id.
Now this exit variable is "ready for Input" . when I debug my code it takes i_step =3 and i_vanm= " " after i_step = 1 and i_vnam = "<variablename>"
how do I go about to get the solution.
Guide me to come up with desired output.
Thanks in Adv.
Bhavna. -
Query to get a value for each day in a month
Hi All,
I'm needing a query (preferably without a loop or function) that can get a number representing each day of a given month.
For example for the month of February, the result would be 1,2,3,....28
Surely this can be done?
Thanks!SQL> with a as (
2 select trunc(sysdate,'Month') mon from dual)
3 SELECT mon + LEVEL - 1 AS dates
4 FROM a
5 CONNECT BY LEVEL <= ADD_MONTHS (mon, 1) - mon;
DATES
01-FEB-11
02-FEB-11
03-FEB-11
04-FEB-11
05-FEB-11
06-FEB-11
07-FEB-11
08-FEB-11
09-FEB-11
10-FEB-11
11-FEB-11
DATES
12-FEB-11
13-FEB-11
14-FEB-11
15-FEB-11
16-FEB-11
17-FEB-11
18-FEB-11
19-FEB-11
20-FEB-11
21-FEB-11
22-FEB-11
DATES
23-FEB-11
24-FEB-11
25-FEB-11
26-FEB-11
27-FEB-11
28-FEB-11
28 rows selected.or if u want it in one query,Then
SQL> SELECT trunc(sysdate,'Month') + LEVEL - 1 AS dates
2 FROM dual
3 CONNECT BY LEVEL <= ADD_MONTHS (trunc(sysdate,'Month'), 1) - trunc(sysdate,'Month');
DATES
01-FEB-11
02-FEB-11
03-FEB-11
04-FEB-11
05-FEB-11
06-FEB-11
07-FEB-11
08-FEB-11
09-FEB-11
10-FEB-11
11-FEB-11
DATES
12-FEB-11
13-FEB-11
14-FEB-11
15-FEB-11
16-FEB-11
17-FEB-11
18-FEB-11
19-FEB-11
20-FEB-11
21-FEB-11
22-FEB-11
DATES
23-FEB-11
24-FEB-11
25-FEB-11
26-FEB-11
27-FEB-11
28-FEB-11
28 rows selected.
SQL> Regards
Umesh -
SQL Query for getting Row No for each group
Dear Oracle Gurus,
I want to allocate Rownum to each group. How we can do this with single SQL. Help me on this.
Thanksselect deptno, ename, row_number() over (partition by deptno order by ename) from emp order by 1,3;
-
Getting the first row for each group
Hi Everyone,
I have a query which returns a number of rows, all of which are valid. What I need to do is to get the first row for each group and work with those records.
For example ...
client flight startairport destairport stops
A fl123 LGW BKK 2
A fl124 LHR BKK 5
B fl432 LGW XYZ 7
B fl432 MAN ABC 8
.... etc.
I would need to return one row for Client A and one row for Client B (etc.) but find that I can't use the MIN function because it would return the MIN value for each column (i.e. mix up the rows). I also can use the rownum=1 because this would only return one row rather than one row per group (i.e. per client).
I have been investigating and most postings seem to say that it needs a second query to look up the first row for each grouping. This is a solution which would not really be practical because my query is already quite complex and incorporating duplicate subqueries would just make the whole thing much to cumbersome.
So what I really new is a "MIN by group" or a "TOP by group" or a "ROWNUM=1 by group" function.
Can anyone help me with this? I'm sure that there must be a command to handle this.
Regards and any thanks,
Alan Searle
Cologne, GermanySomething like this:
select *
from (
select table1.*
row_number() over (partition by col1, col2 order by col3, col4) rn
from table1
where rn = 1In the "partition by" clause you place what you normally would "group by".
In the "order by" clause you define which will have row_number = 1.
Edit:
PS. The [url http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/functions004.htm#i81407]docs have more examples on using analytical functions ;-)
Edited by: Kim Berg Hansen on Sep 16, 2011 10:46 AM -
Information in Template Header with value from 3 for-each groups
Hi,
i have an datamodel with 3 nested groups and in my rtf-template i'm using 3 for each-loops to give the data out.
It works fine, i can show the data on every level.
But now our customers wants in the Header of each page information with values from each group.
Like Land-District-City.
My first Test was with the @section-condition to get the right data in the Header.
But it only works fine for the first group and not further....
Anybody an idea? May be more then one @section?
Regards ChristianHi Mike,
I found some two mistakes that should solve your problems:
1. typo: use "raw_value" with underscore, then the "category" works.
2. The array support of the Generic Panel is limited to semicolon-separated term lists in a text field,
where each term represent an array item.
For example the "supplemental categories" property should look like:
<xmp_property
name="SupplementalCategories" category="external"
label="$$$/stewart/Class=Classification:" type="bag" element_type="text"
xmp_path="SupplementalCategories" ui:multiLine="true" ui:mru="true" description="..."
/>
Hope this helps,
-- Stefan -
How to compare the value node of a for-each-group with other for-each-group
Hello!
I have a report in Oracle BI Publisher (10.1.3.2) with several data set. My XML schema is something like
<DATA>
<PARAMETERS>
<MY_PARAMETERS>
<A_ID>12345</A_ID>
<DESCRIPTION>ABC</DESCRIPTION>
<VALUE>111111</VALUE>
</MY_PARAMETERS>
<MY_PARAMETERS>
<A_ID>12345</A_ID>
<DESCRIPTION>DEF</DESCRIPTION>
<VALUE>222222</VALUE>
</MY_PARAMETERS>
<MY_PARAMETERS>
<A_ID>67890</A_ID>
<DESCRIPTION>ABC</DESCRIPTION>
<VALUE>333333</VALUE>
</MY_PARAMETERS>
</PARAMETERS>
<NAMES>
<MY_NAMES>
<A_ID>12345</A_ID>
<NAME>ASDF</NAME>
</MY_NAMES>
<MY_NAMES>
<A_ID>67890</A_ID>
<NAME>EFGH</NAME>
</MY_NAMES>
</NAMES>
<VALUES>
<MY_VALUES>
<A_ID>12345<A_ID>
<VALUE>10987</VALUE>
<DESCRIPTION>ASDFG</DESCRIPTION>
</MY_VALUES>
<MY_VALUES>
<A_ID>12345<A_ID>
<VALUE>26385</VALUE>
<DESCRIPTION>EFGHI</DESCRIPTION>
</MY_VALUES>
<MY_VALUES>
<A_ID>67890<A_ID>
<VALUE>24355</VALUE>
<DESCRIPTION>ASDFG</DESCRIPTION>
</MY_VALUES>
</VALUES>
</DATA>
I'm trying to build a rtf template in Word using this XML schema. The "A_ID" nodes in each group in my data have the same value. I want for each "A_ID" take the respective values in /DATA/VALUES/MY_VALUES.
<?for-each-group:MY_PARAMETERS;./A_ID?>
<?for-each:current-group()?>
<?choose:?><?when: DESCRIPTION='ABC'?>
<?VALUE?>
<?end when?><?end choose?>
<?end for-each?>
<?for-each:current-group()?>
<?choose:?><?when: DESCRIPTION='DEF'?>
<?VALUE?>
<?end when?><?end choose?>
<?end for-each?>
<?/DATA/NAMES/MY_NAMES/VALUE?>
<?for-each-group:/DATA/VALUES/MY_VALUES;./A_ID?>
<?for-each:current-group()?>
<?choose:?><?when: DESCRIPTION='ASDFG'?>
<?VALUE?> <---------------- I obtain for this node the '24355' and '10987' values
<?end when?><?end choose?>
I want to know how to obtain only '24355' value, this is, the value for A_ID (/DATA/VALUES/MY_VALUES) = A_ID (/DATA/PARAMETERS/MY_PARAMETERS).
Can someone help me?CREATE OR REPLACE TRIGGER "TEST_TRG"
BEFORE UPDATE OF "STATUS"
ON "TABLE1"
FOR EACH ROW
BEGIN
IF (:NEW.status = 'HOLD')
THEN
INSERT INTO table2
(status
VALUES (:NEW.status
END IF;
END;You should learn how to write PL/SQL code.
Denes Kubicek
http://deneskubicek.blogspot.com/
http://www.apress.com/9781430235125
http://apex.oracle.com/pls/apex/f?p=31517:1
http://www.amazon.de/Oracle-APEX-XE-Praxis/dp/3826655494
------------------------------------------------------------------- -
Last() not returning correct value within for-each-group
I've found inconsistent results between JDeveloper and SOA Suite using the xslt 2.0 for-each-group construct.
<xsl:for-each-group select="Po/PoLine" group-by="itemId">
<xsl:if test="position()=1">
<GroupCount>
<xsl:value-of select="last()"/>
</GroupCount>
</xsl:if>
</xsl:for-each-group>
What I expect is the function last() to give me the number of groups which is the unique number of itemIds.
In JDeveloper 10.1.3.4, testing this construct gives me what I expect.
At run-time (deployed to 10.1.3.3 SOA Suite), the value returned is the total number of records, not the number of groups.
For example, given the following XML
<Po>
<PoLine>
<itemId><strong>001</strong></itemId>
<description>Hammer</description>
<quantity>10</quantity>
</PoLine>
<PoLine>
<itemId><strong>001</strong></itemId>
<description>Hammer</description>
<quantity>10</quantity>
</PoLine>
<PoLine>
<itemId><strong>002</strong></itemId>
<description>Nail</description>
<quantity>10</quantity>
</PoLine>
</Po>
Grouping by <strong>itemId</strong>, last() should return 2 as there are two groups (001 and 002). JDeveloper does this.
When deployed to SOA Suite, last() returns 3.
Any ideas?Hi,
if JDeveloper is doing the right thing then this issue should be reported to the SOA Suite forum or BPEL BPEL , what do you think ?
Frank -
How to get Privacy Policy value for each userprofile in sharepoint 2010?
In userprofile application, we have defined Privacy Policy of mobilephone feild as optional, so every user has option to choose visibility scope of this property to "Everyone/My Manager/my colegues/Only Me" .
Now I am trying to get mobilephone value and their selected visibility option for each user.
I am able to get mobilephone value but I could not get "what each user has chosen as their visibility scope"?Hi,
According to your post, my understanding is that you want to get Privacy Policy value for each userprofile in sharepoint 2010.
You need to use RunWithElevatedPrivileges method to impersonate user.
To get the get mobilephone policy, you can use user["CellPhone "].Privacy.
For more information, you can refer to:
c# - Getting property privacy with Sharepoint 2010
How to Programmatically Impersonate Users in SharePoint
Managing Sharepoint 2010 Profiles Programmatically
Thanks,
Linda Li
Forum Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
[email protected]
Linda Li
TechNet Community Support -
Find out and get the bit value for each pixel in image
i use 16bit image. the image is 200x200 pixels. i need to know what is
the bit value for each pixel. example(0111111011111101).
where i can see the bit value output. if somebody got the example surce code please send it to me.coz i need the bit value to find out how many RGB color that use in the image. thanks for ur help.How many logins do you have???
-
How to Get Missing Dates for Each Support Ticket In My Query?
Hello -
I'm really baffled as to how to get missing dates for each support ticket in my query. I did a search for this and found several CTE's however they only provide ways to find missing dates in a date table rather than missing dates for another column
in a table. Let me explain a bit further here -
I have a query which has a list of support tickets for the month of January. Each support ticket is supposed to be updated daily by a support rep, however that isn't happening so the business wants to know for each ticket which dates have NOT been
updated. So, for example, I might have support ticket 44BS which was updated on 2014-01-01, 2014-01-05, 2014-01-07. Each time the ticket is updated a new row is inserted into the table. I need a query which will return the missing dates per
each support ticket.
I should also add that I DO NOT have any sort of admin nor write permissions to the database...none at all. My team has tried and they won't give 'em. So proposing a function or storable solution will not work. I'm stuck with doing everything
in a query.
I'll try and provide some sample data as an example -
CREATE TABLE #Tickets
TicketNo VARCHAR(4)
,DateUpdated DATE
INSERT INTO #Tickets VALUES ('44BS', '2014-01-01')
INSERT INTO #Tickets VALUES ('44BS', '2014-01-05')
INSERT INTO #Tickets VALUES ('44BS', '2014-01-07')
INSERT INTO #Tickets VALUES ('32VT', '2014-01-03')
INSERT INTO #Tickets VALUES ('32VT', '2014-01-09')
INSERT INTO #Tickets VALUES ('32VT', '2014-01-11')
So for ticket 44BS, I need to return the missing dates between January 1st and January 5th, again between January 5th and January 7th. A set-based solution would be best.
I'm sure this is easier than i'm making it. However, after playing around for a couple of hours my head hurts and I need sleep. If anyone can help, you'd be a job-saver :)
Thanks!!CREATE TABLE #Tickets (
TicketNo VARCHAR(4)
,DateUpdated DATETIME
GO
INSERT INTO #Tickets
VALUES (
'44BS'
,'2014-01-01'
INSERT INTO #Tickets
VALUES (
'44BS'
,'2014-01-05'
INSERT INTO #Tickets
VALUES (
'44BS'
,'2014-01-07'
INSERT INTO #Tickets
VALUES (
'32VT'
,'2014-01-03'
INSERT INTO #Tickets
VALUES (
'32VT'
,'2014-01-09'
INSERT INTO #Tickets
VALUES (
'32VT'
,'2014-01-11'
GO
GO
SELECT *
FROM #Tickets
GO
GO
CREATE TABLE #tempDist (
NRow INT
,TicketNo VARCHAR(4)
,MinDate DATETIME
,MaxDate DATETIME
GO
CREATE TABLE #tempUnUserdDate (
TicketNo VARCHAR(4)
,MissDate DATETIME
GO
INSERT INTO #tempDist
SELECT Row_Number() OVER (
ORDER BY TicketNo
) AS NROw
,TicketNo
,Min(DateUpdated) AS MinDate
,MAx(DateUpdated) AS MaxDate
FROM #Tickets
GROUP BY TicketNo
SELECT *
FROM #tempDist
GO
-- Get the number of rows in the looping table
DECLARE @RowCount INT
SET @RowCount = (
SELECT COUNT(TicketNo)
FROM #tempDist
-- Declare an iterator
DECLARE @I INT
-- Initialize the iterator
SET @I = 1
-- Loop through the rows of a table @myTable
WHILE (@I <= @RowCount)
BEGIN
-- Declare variables to hold the data which we get after looping each record
DECLARE @MyDate DATETIME
DECLARE @TicketNo VARCHAR(50)
,@MinDate DATETIME
,@MaxDate DATETIME
-- Get the data from table and set to variables
SELECT @TicketNo = TicketNo
,@MinDate = MinDate
,@MaxDate = MaxDate
FROM #tempDist
WHERE NRow = @I
SET @MyDate = @MinDate
WHILE @MaxDate > @MyDate
BEGIN
IF NOT EXISTS (
SELECT *
FROM #Tickets
WHERE TicketNo = @TicketNo
AND DateUpdated = @MyDate
BEGIN
INSERT INTO #tempUnUserdDate
VALUES (
@TicketNo
,@MyDate
END
SET @MyDate = dateadd(d, 1, @MyDate)
END
SET @I = @I + 1
END
GO
SELECT *
FROM #tempUnUserdDate
GO
GO
DROP TABLE #tickets
GO
DROP TABLE #tempDist
GO
DROP TABLE #tempUnUserdDate
Thanks,
Shridhar J Joshi
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'> -
I'm trying to get the count for each row to total count for each month
Something like this
Hardware | Jan
Monitors | 5
Processors | 137
Printers | 57
etc........
How can I write a query for this. I can get the Hardware column but don't know how to get the next column.If you can provide more data like sample input DML statements it would have been wonderful..
Assuming is , you need a pivot. Here is an article on basic Pivot..
http://sqlsaga.com/sql-server/how-to-use-pivot-to-transform-rows-into-columns-in-sql-server/
something like this may be..
DECLARE @Input TABLE
Hardware VARCHAR(20),
[Date] VARCHAR(20)
INSERT INTO @Input VALUES('Monitor', '01/01/2014'), ('CPU', '01/01/2014'), ('Monitor', '01/03/2014')
, ('ABC', '01/01/2014'),('Monitor', '02/01/2014')
;WITH CTE AS
SELECT Hardware, LEFT(DATENAME(M, [Date]),3) AS [MonthName] FROM @Input
SELECT *
FROM
SELECT Hardware, [MonthName], COUNT(Hardware) AS Count FROM CTE GROUP BY Hardware, [MonthName]) a
PIVOT (MAX([Count]) FOR [MonthName] IN ([Jan], [Feb])) pvt
Please mark as answer, if this has helped you solve the issue.
Good Luck :) .. visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles. -
How to handle goup sub total for each group in oracle query ?
hi,
i want to handle one complex thing in oracle query.
i have a grouping in my oracle query.
i want to do sub total for each group in query and after that i want to subtract one group sub total from previous group subtotal ?
so how can i handle this in oracle query ?
any help is greatly appreciated.
thanks.Hello
Interesting requirement.
I wonder why are you not using these calculation during the display time. If it is acceptable then you can try using the custom formula with the running total combination in crystral report to achieve to get the required results.
Best regards
Ali Hadi
Maybe you are looking for
-
Hello there, my iphone has stolen and i want to stop it at all
hello there, my iphone has stolen and i want to stop it at all here is my imei imei 358763053881745 please i want to stop the service on this device as soon as possible ..
-
Owa_util.ident_arr
Does anyone know how to use this datatype? From what I understand, I use this to capture multiple selections from a drop list. That's all well and good, but is there any way to convert that into a string (delimited) that I can stick into a database c
-
Multiple cells that reference one value
Hey guys - Still new to formulas - any help would be appreciated. I have a cell on table 1, with the cell value duplicated in other tables / sheets in my document. For example, Cell A1 in tables 2 & 3 is referencing back to table 1, using the formula
-
When I place a call or receive a call, all I get is silence.
I received my Samsung Galaxy s 4 today and I found that when I placed or received a call, I would pick it up or the the other party would and neither of us could hear the other. About one in a dozen calls could be heard and when I restarted the
-
External disk for iPad available?
Is there an external disk for iPad now? Not like in two years.