Assign values based on data range
Hi
I am trying to fix a query that I ahve been left with from a previous developer.
The basis of it are that I have 2 views, one which is effectively a date calendar with users per date, and the 2nd being values assigned between a 2 date ranges.
here is sample data
create table #hours (
Fee_earner_Code int not null
,startdate date not null
,enddate date not null
,hours decimal (17,2) not null
insert into #hours values (1132,'2011-06-01','2020-01-01',6.00)
insert into #hours values (1132,'2011-06-07','2011-06-01',4.00)
insert into #hours values (1132,'2012-06-09','2011-06-07',12.00)
insert into #hours values (2345,'2011-06-01','2020-01-01',3.00)
insert into #hours values (2345,'2011-06-06','2011-06-01',9.00)
insert into #hours values (2345,'2012-06-10','2011-06-06',5.00)
create table #dates (Fee_earner_Code int not null
,Primary_date date not null
insert into #dates values (1132,'2011-06-01')
insert into #dates values (1132,'2011-06-02')
insert into #dates values (1132,'2011-06-03')
insert into #dates values (1132,'2011-06-04')
insert into #dates values (1132,'2011-06-05')
insert into #dates values (1132,'2011-06-06')
insert into #dates values (1132,'2011-06-07')
insert into #dates values (1132,'2011-06-08')
insert into #dates values (1132,'2011-06-09')
insert into #dates values (1132,'2011-06-10')
insert into #dates values (1132,'2011-06-11')
insert into #dates values (1132,'2011-06-12')
insert into #dates values (2345,'2011-06-01')
insert into #dates values (2345,'2011-06-02')
insert into #dates values (2345,'2011-06-03')
insert into #dates values (2345,'2011-06-04')
insert into #dates values (2345,'2011-06-05')
insert into #dates values (2345,'2011-06-06')
insert into #dates values (2345,'2011-06-07')
insert into #dates values (2345,'2011-06-08')
insert into #dates values (2345,'2011-06-09')
insert into #dates values (2345,'2011-06-10')
insert into #dates values (2345,'2011-06-11')
insert into #dates values (2345,'2011-06-12')
for the table #hours the end date is alway the previous rows startdate unless it is the 1st row per fee_earner_Code then it is assigned '2020-01-01' (this date can be change as it is just another view)
I would like to apply the #hours hours value to the appropriate date range in #dates per fee-earner-code
my expected ouput would be
1132,2011-06-01,6.00
1132,2011-06-02,6.00
1132,2011-06-03,6.00
1132,2011-06-04,6.00
1132,2011-06-05,6.00
1132,2011-06-06,6.00
1132,2011-06-07,4.00
1132,2011-06-08,6.00
1132,2011-06-09,12.00
1132,2011-06-10,12.00
1132,2011-06-11,12.00
1132,2011-06-12,12.00
2345,2011-06-01,3.00
2345,2011-06-02,3.00
2345,2011-06-03,3.00
2345,2011-06-04,3.00
2345,2011-06-05,3.00
2345,2011-06-06,9.00
2345,2011-06-07,9.00
2345,2011-06-08,9.00
2345,2011-06-09,9.00
2345,2011-06-10,5.00
2345,2011-06-11,5.00
2345,2011-06-12,5.00
Any help would be great
With SQL Server 2012's Windows functions, this becomes easy. We can use it to fix the data in your hours table:
DECLARE @hours TABLE (Fee_earner_Code int not null, startdate date not null, enddate date not null, hours decimal (17,2) not null)
INSERT INTO @hours (Fee_earner_Code, startdate, enddate, hours) VALUES (1132,'2011-06-01','2020-01-01',6.00),(1132,'2011-06-07','2011-06-01',4.00),(1132,'2012-06-09','2011-06-07',12.00),(2345,'2011-06-01','2020-01-01',3.00),(2345,'2011-06-06','2011-06-01',9.00),(2345,'2012-06-10','2011-06-06',5.00)
DECLARE @dates TABLE (Fee_earner_Code int not null, Primary_date date not null)
INSERT INTO @dates (Fee_earner_Code, Primary_date) VALUES (1132,'2011-06-01'),(1132,'2011-06-02'),(1132,'2011-06-03'),(1132,'2011-06-04'),(1132,'2011-06-05'),(1132,'2011-06-06'),(1132,'2011-06-07'),(1132,'2011-06-08'),
(1132,'2011-06-09'),(1132,'2011-06-10'),(1132,'2011-06-11'),(1132,'2011-06-12'),(2345,'2011-06-01'),(2345,'2011-06-02'),(2345,'2011-06-03'),(2345,'2011-06-04'),
(2345,'2011-06-05'),(2345,'2011-06-06'),(2345,'2011-06-07'),(2345,'2011-06-08'),(2345,'2011-06-09'),(2345,'2011-06-10'),(2345,'2011-06-11'),(2345,'2011-06-12')
;WITH fixHours AS (
SELECT *, DATEADD(DAY,-1,LEAD(startDate) OVER (PARTITION BY Fee_earner_code ORDER BY startDate)) AS realEndDate
FROM @hours h
SELECT h.Fee_earner_Code, d.Primary_date, h.hours
FROM fixHours h
LEFT OUTER JOIN @dates d
ON d.Primary_date BETWEEN h.startDate AND realEndDate
Without it, we need to do a self join to acheive the same end:
DECLARE @hours TABLE (Fee_earner_Code int not null, startdate date not null, enddate date not null, hours decimal (17,2) not null)
INSERT INTO @hours (Fee_earner_Code, startdate, enddate, hours) VALUES (1132,'2011-06-01','2020-01-01',6.00),(1132,'2011-06-07','2011-06-01',4.00),(1132,'2012-06-09','2011-06-07',12.00),(2345,'2011-06-01','2020-01-01',3.00),(2345,'2011-06-06','2011-06-01',9.00),(2345,'2012-06-10','2011-06-06',5.00)
DECLARE @dates TABLE (Fee_earner_Code int not null, Primary_date date not null)
INSERT INTO @dates (Fee_earner_Code, Primary_date) VALUES (1132,'2011-06-01'),(1132,'2011-06-02'),(1132,'2011-06-03'),(1132,'2011-06-04'),(1132,'2011-06-05'),(1132,'2011-06-06'),(1132,'2011-06-07'),(1132,'2011-06-08'),
(1132,'2011-06-09'),(1132,'2011-06-10'),(1132,'2011-06-11'),(1132,'2011-06-12'),(2345,'2011-06-01'),(2345,'2011-06-02'),(2345,'2011-06-03'),(2345,'2011-06-04'),
(2345,'2011-06-05'),(2345,'2011-06-06'),(2345,'2011-06-07'),(2345,'2011-06-08'),(2345,'2011-06-09'),(2345,'2011-06-10'),(2345,'2011-06-11'),(2345,'2011-06-12')
;WITH fixHours AS (
SELECT h.*, DATEADD(DAY,-1,h1.startdate) as realEndDate
FROM @hours h
INNER JOIN @hours h1
ON h.Fee_earner_Code = h1.Fee_earner_Code
AND h1.startdate = (SELECT MIN(startDate) FROM @hours WHERE h1.Fee_earner_Code = Fee_earner_Code AND h.startdate < startDate)
SELECT h.Fee_earner_Code, d.Primary_date, h.hours
FROM fixHours h
LEFT OUTER JOIN @dates d
ON d.Primary_date BETWEEN h.startDate AND realEndDate
Similar Messages
-
To select from database table based on date range
hi
i have a selection screen in which date range is being given
say eg 23/06/07 to 23/12/08
based on this date i want to select data from a ztable
eg i want to select a field amount from table
and three is a field date range on the table
for this particular field i want to select all records for amount field and factual field falling wiithing this date range and sum it
eg
based on date range as in selcetion screen
select amount( field1) factual ( field2) from ztable into it_ztable where date = ?....
please give me code for it and how to sum all values as i will get from the ztable into internal table the two values as fetched from the ztable
please suggest asap
regards
arorahi
i am using
sELECT field1 field2 FROM Ztable INto it_matu
where DATE GE sl_dat-low
AND DATE LE sl_dat-high.
i am getting data in internal table but
say i have twelve records now i want to sum it the both the columns into and use that sum final amount to display
let me know how to use sume in the intrranal tabl do i need to use control statement
how to use the sum for two columns and take into a serperate variable to display
regards
aRora -
Query to split one row to multiple based on date range
Hi,
I need to split single row into multple based on date range defined in a column, start_dt and end_dt
I have a data
ID From date End_dt measure
1 2013-12-01 2013-12-03 1
1 2013-12-04 2013-12-06 2
2 2013-12-01 2013-12-02 11
3 2013-12-03 2013-12-04 22
I required output as
ID Date measure
1 2013-12-01 1
1 2013-12-02 1
1 2013-12-03 1
1 2013-12-04 2
1 2013-12-05 2
1 2013-12-06 2
2 2013-12-01 11
2 2013-12-02 11
3 2013-12-03 22
3 2013-12-04 22
Please provide me sq, query for the same
Amit
Please mark as answer if helpful
http://fascinatingsql.wordpress.com/Have a calendar table for example and then probably using UNION ALL from date and stat date JOIN the Calendar table
SELECT ID,From date FROM tbl
union all
SELECT ID,End_dt FROM tbl
with tmp(plant_date) as
select cast('20130101' as datetime)
union all
select plant_date + 1
from tmp
where plant_date < '20131231'
select*
from tmp
option (maxrecursion 0)
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 -
Displaying different sums in the same row based on date ranges
Say I had a table like this
DECLARE @t1 TABLE (RowId INT PRIMARY KEY IDENTITY(1,1), BusinessType VARCHAR(100), SalesPerson VARCHAR(100), Category VARCHAR(100), OrderAmount DECIMAL(10,2), OrderDate DATETIME )
Now I want to get a result that is grouped first by BusinessType, then SalesPerson and include derived columns that are sums based on different date ranges.
Month-to-date = from the start of the current month to today
Month-to-date previous year = from the start of the current month to today 1 year ago
DECLARE @today DATETIME
DECLARE @today_prev_year DATETIME
DECLARE @year_start DATETIME
DECLARE @year_prev_start DATETIME
DECLARE @month_start DATETIME
DECLARE @month_prev_start DATETIME
SET @today = GETDATE();
SET @today_prev_year = DATEADD(YEAR,-1,@today)
SET @year_start = CAST('01/01/' + CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR(10)) AS DATETIME);
SET @year_prev_start = DATEADD(YEAR,-1,@year_start)
SET @month_start = DATEADD(month, DATEDIFF(month, 0, @today), 0); --gets the first of the current month
SET @month_prev_start = DATEADD(YEAR,-1,@month_start); --gets the first of the current month
SELECT t.BusinessType,t.SalesPerson,t.Category
SUM(CASE WHEN o.OrderDate > @month_start AND ac.DocumentDate < @today THEN o.OrderAmount ELSE 0 END) AS MTDActualAmount
SUM(CASE WHEN o.OrderDate > @month_prev_start AND ac.DocumentDate < @today_prev_year THEN o.OrderAmount ELSE 0 END) AS MTDPrevActualAmount
FROM @t1 t
Hope this is clear as to what Im trying to do. Im ultimately going to pull this into an SSRS report, so im wondering if I can do this different SUM values in the report and handle the grouping there.
Thoughts?Based on your example (with a group by added) it should work.
However, if you incorperated a calendar table (http://social.technet.microsoft.com/wiki/contents/articles/29260.tsql-calendar-functions-and-tables.aspx)
you could lose all those manually set parameters:
DECLARE @t1 TABLE (RowId INT PRIMARY KEY IDENTITY(1,1), BusinessType VARCHAR(100), SalesPerson VARCHAR(100), Category VARCHAR(100), OrderAmount DECIMAL(10,2), OrderDate DATETIME, DocumentDate DATETIME)
INSERT INTO @t1 (BusinessType, SalesPerson, Category, OrderAmount, OrderDate, DocumentDate) VALUES
('A','Joe','CatA',10,'2015-01-01','2015-01-01'),('A','Joe','CatB',10,'2015-01-02','2015-01-01'),('A','Joe','CatA',30,'2015-01-03','2015-01-04'),('A','Joe','CatB',40,'2015-01-04','2015-01-01'),('A','Joe','CatA',100,'2015-02-01','2015-02-01'),
('A','Joe','CatB',100,'2015-02-02','2015-02-01'),('A','Joe','CatA',300,'2015-02-03','2015-02-04'),('A','Joe','CatB',400,'2015-02-04','2015-02-01'),('A','Bob','CatA',1,'2015-01-01','2015-01-01'),('A','Bob','CatB',1,'2015-01-02','2015-01-01'),
('A','Bob','CatA',3,'2015-01-03','2015-01-04'),('A','Bob','CatB',4,'2015-01-04','2015-01-01'),('A','Bob','CatA',10,'2015-02-01','2015-02-01'),('A','Bob','CatB',10,'2015-02-02','2015-02-01'),('A','Bob','CatA',30,'2015-02-03','2015-02-04'),
('A','Bob','CatB',40,'2015-02-04','2015-02-01'),('B','Joe','CatA',10,'2015-01-01','2015-01-01'),('B','Joe','CatB',10,'2015-01-02','2015-01-01'),('B','Joe','CatB',40,'2015-01-04','2015-01-01'),
('B','Joe','CatA',100,'2015-02-01','2015-02-01'),('B','Joe','CatB',100,'2015-02-02','2015-02-01'),('B','Joe','CatA',300,'2015-02-03','2015-02-04')
SELECT t.BusinessType,t.SalesPerson,t.Category,
SUM(CASE WHEN OrderDate >= monthStart AND DocumentDate < today THEN OrderAmount ELSE 0 END) AS MTDActualAmount,
SUM(CASE WHEN OrderDate BETWEEN prevMonthStart AND prevMonthENd AND DocumentDate >= yearStart THEN OrderAmount ELSE 0 END) AS MTDPrevActualAmount
FROM @t1 t
INNER JOIN calendar c
ON today = CAST(CURRENT_TIMESTAMP AS DATE)
Group by t.BusinessType,t.SalesPerson,t.Category -
User-filtered report based on date range
I am struggling with trying to implement a basic search that includes an optional date range for the data. The form looks the way I want it, but I can't seem to get the right syntax in the query. I can't get anything other than "no rows" to show up in the query if I implement a clause selecting records based on the time.
Here is a working query (without the time):
select m.AUDIT_ID, m.TIMESTAMP, m.LOC_ID, a.AREA, s.SUBAREA, d.OBSERVATIONS
from transys.SAFETY_AUDIT_MAIN m, transys.SAFETY_AUDIT_DETAIL d,
transys.SAFETY_AUDIT_AREA a, transys.SAFETY_AUDIT_SUBAREA s
where m.AUDIT_ID = d.AUDIT_ID (+)
and d.AREA_ID = a.AREA_ID
and d.SUBAREA_ID = s.SUBAREA_ID
and s.SUBAREA_ID NOT IN (198,199,398,399,498,499,798,799,898,899,999)
and (instr(upper(a.AREA),upper(nvl(:P210_SEARCH,AREA))) > 0
or instr(upper(s.SUBAREA),upper(nvl(:P210_SEARCH,SUBAREA))) > 0
or instr(upper(d.OBSERVATIONS),upper(nvl(:P210_SEARCH,OBSERVATIONS))) > 0)
I want to compare the m.TIMESTAMP column with page items P210_FROM_DATE and P210_TO_DATE.
I would also like to add in an optional filter comparing m.LOC_ID to P210_LOCATION, and I can't seem to figure out the "optional" part.
Any ideas would be helpful.The query as I posted it returns 3 values, but it is not syntactically identical to the one APEX is using. I would be happy to get 3 rows in APEX because at least that way I would know I have the date formatting correct, and just needed to tweak the logic. When I execute the query in APEX, however, I get either "there is no data to display" or I get a formatting error - "X is not a valid month" - depending on how I use TO_CHAR and TO_DATE to try and synchronize the various date inputs with the field.
If it is a query issue (which it may be), I am still suspecting that it is something to do with the formatting of the dates involved. Just as in APEX, it could be something simple, but I suspect it is a mismatch in the formatting somewhere.
Maybe I'll try making a view of the underlying table and experimenting with the date in the view. That should enable me to see if it is the formatting in the query or the formatting in APEX that is causing the problem. Or it could even eliminate formatting as the problem as well.
PS. I had a similar struggle trying to implement some triggers against this database that used date values. NLS_TIMESTAMP_FORMAT is set to 'YYYY-MM-DD HH24.MI.SS.FF'. I ended up converting every date that I pulled from the database into a known format with TO_CHAR and then converting it back into a date with TO_DATE. It was the only way to be able to compare the date values without getting these same kinds of errors. -
Assign Month within a date range (by most days in a given month)
I have a begin and end date, sample data as such
select to_date('01-13-12','mm-dd-yy') from_dt,
to_date('02-23-12','mm-dd-yy') to_dt
from dual
union all
select to_date('03-15-2012','mm-dd-yy') from_dt,
to_date('04-16-2012','mm-dd-yy') to_dt
from dual
union all
select to_date('05-13-2012','mm-dd-yy') from_dt,
to_date('07-23-2012','mm-dd-yy') to_dt
from dual
How do I assign a month by the most days in a month within that date range? Sometimes the date range might have the exact same amount of days in a month (like 3/15/2012 has 16 days and 4/16/2012 has 16 days). In this case, I want the earlier month (march).
So from the sample data:
01/13/2012, 02/23/2012, February
03/15/2012, 04/16/2012, March
05/13/2012, 07/23/2012, June
Thanks
Edited by: user4422426 on Mar 1, 2012 5:15 PMHi,
Here's one way:
WITH cntr AS
SELECT LEVEL - 1 AS n
FROM (
SELECT 1 + MAX (to_dt - from_dt) AS max_day_cnt
FROM table_x
CONNECT BY LEVEL <= max_day_cnt
, got_r_num AS
SELECT x.from_dt, x.to_dt
, TRUNC (x.from_dt + c.n, 'MONTH') AS month
, count (*) AS cnt
, ROW_NUMBER () OVER ( PARTITION BY from_dt, to_dt
ORDER BY COUNT (*) DESC
, TRUNC (x.from_dt + c.n, 'MONTH')
) AS r_num
FROM cntr c
JOIN table_x x ON c.n <= x.to_dt - x.from_dt
GROUP BY x.from_dt, x.to_dt
, TRUNC (x.from_dt + c.n, 'MONTH')
SELECT from_dt, to_dt
, TO_CHAR (month, 'Mon YYYY') AS mon
, cnt
FROM got_r_num
WHERE r_num = 1
;Thanks for posting code to create the same data. Please test your code before you post it: you got the order of arguments to TO_DATE reversed. -
Supress details in subreport based on date ranges in main report
I am using Crystal XI R2 and am working with Human Resources Data.
The main report is grouped on and generates a list of temporary teaching positions like this:
Smith, John
FTE_____Start Date_______End Date
.3 ______09/01/2007______10/20/2007
.2 ______10/05/2007 ______04/15/2008
.2 ______04/01/2008 ______06/30/2008
The subreport (generated from a different source, but linked to main report on ) generates a list of days the employee worked as a Teacher on Call:
TOC Date______ Portion of Day Worked
09/05/2007______1.0
09/19/2007______0.6
10/08/2007______0.4
10/09/2007______1.0
04/08/2008______0.6
04/18/2008______1.0
Employees are granted seniority for TOC days worked, EXCEPT when they are already employed in a Teaching position >=.4 FTE (because they are already granted full seniority for that period), so I need to be able to suppress records that fall within date ranges listed in the Main Report where the combine FTE is >=.4.
I believe this question has two parts:
1. how do I evaluate the date ranges to combine overlapping periods? Results would look like this... (I don't need to be able to see this, but I'm assuming I'd have to create a date range with the results in order to answer question #2 - but I haven't worked much with ranges.)
FTE_____Start Date______End Date
.3______09/01/2007______10/04/2007
.5______10/05/2007______10/20/2007
.2______10/21/2007______03/31/2008
.4______04/01/2008______04/15/2008
.2______04/16/2008______06/30/2008
2. how do I supress the TOC dates in the Subreport that fall within the start and end dates of all the employee's positions >= 0.4 FTE ? Supreport results for this example would look like this...
TOC Date______ Portion of Day Worked
09/05/2007______1.0
09/19/2007______0.6
04/18/2008______1.0
(I will sum the "portion" values and mulitply them by a constant variable to complete the seniority calculation.)
Thank you in advance for any assistance you may be able to provide!Thanks for your help Graham, I have continued to work with this and I took the BO Crystal III course. Your suggestions gave me a sense of direction.
I was not able to share a date range array with the subreport (kept getting error messages saying "call BO" , but I WAS able to share the startdate array and the enddate array. I also shared the fte values array.
I had wanted to use a loop to check
if TOCdate in startarray[x] to endarray[x]
then ftearray[x]
and sum the new range of fte[x] values so that I could suppress any TOCdates where fte was >=0.4. But I couldn't quite get there, I kept coming up with formulas that displayed only the first value or the last or zero.
So I used the following formula for each index (returnindex value had to be changed for each case), then added them all together.
shared datevar array startArray;
shared datevar array endArray;
shared numbervar array FTEArray;
local numbervar arraylength:= ubound(startArray);
local numbervar i;
local numbervar returnindex :=-1;
If arraylength >=1 then
if not({AAATDDET.Date} in startarray[1]to endarray[1])then
0 else
if {AAATDDET.Date} in startarray[1]to endarray[1] then
(returnIndex:= i;);
i:=i+1;
if returnindex =0 then
ftearray[1] -
Restrict Query Data based on Date range and Users
Hi All,
I have a few web reports that I need do restrict data based on Users.
In all the queries i have an infoobject 0CALDAY, and a User Entry range variable on it. Because of performance issues I need to restrict the range of dates a User can see. Typically most of users could go to a max date range of 1 month back. But some others would need the ability to see data for much bigger range of dates.
Pls suggest how should i go about with this. Should I have to enforce this at Variable level(user exit).... but then i might have to maintain a table for the users.. Is there any other way of doing it.
thanks
RajAny thoughts ?
-
How can I sum values over a date range?
I want to sum values (revenue) for a range of dates (i.e. for each month). I'm trying to use the MONTH function nested in SUMIF and keep getting an error message. I want it to be SUMIF( MONTH (column of dates), cell with month, column with revenue) and it tells me "all ranges must be the same size". It works if I create a separate column where I extract the month from each date and then compare that to a column with the number of the month, but that is really annoying.
You can use the sumif() function to compute the sum of revenues after the "End Date", the sum of revenues before some date and you can use the sum function to summ all revenue. Then you can combine these into a single formula to get the answer by:
sum between two dates is:
sum("of all revenue") - sumif("before date") - sumif("after date"
Cell B4 of the smaller table =SUM(Revenue)-SUMIF(Date, "<"&B1,Revenue)-SUMIF(Date, ">"&B2,Revenue)
I highlighed cells to show before and after dates to highlight the sumif("after") and sumif("before") -
Moving average price based on date range, site and article.
Hi ABAPers,
I am working on SKU wise sales report. Based on user input of date range ,site and article I fetch data from VBRP table i.e., (billing data from stores) . I have searched a lot to find MAP but dint get convincing solution.
I tried to get data from MBEW-VERPR but that doesnot give MAP for a given date. I also tried with condition record table and KONP table but not helpful.
I also got to know about s031 and LIS configuration I am not sure whether functional consultant should do the changes.
Kindly help me in obtaining the MAP for particular bill date, article and site(store).
Regards,
DepYou can found the moving average price in MBEW (current) and MBEWH (history table)
The first goods movement after the period closing program updates the period in MBEW and writes the data of the previous period to table MBEWH
- If you actually need map on a daily (or less) basis, you will have to calculate it from MBEW, MBEWH, MSEG and BSIM (...)
- You could also look for the actual cost in MSEG related to records of VBRP.
Regards,
Raymond -
Disbaling No upper/lower bound value in a date range parameter
Hi folks,
When i added a new parameter with a date range , i can see two check boxes 'No lower value' and 'No upper value' along with 'include value' checkbox in the parameter dialog.
Is there any way to disable these check boxes?? If i cannot disable check boxes and when i select no lower value check box some random date value get returns to the query and the SQL query is giving no results and also i cannot set to a default lower and upper date range too.
Please help me in resolving this.
Thanks in advance.These features are respective to the range component. If you do not need them, I would suggest that you use two date parameters. One date parameter can act as your low date parameter, and can have it's own default date. The other parameter can act as your high date parameter, and can have it's own default value.
The only change essentially, in the way the report runs, should be some minor changes to formulas, for example instead of having a selection criteria formula that says in {?DateRange}, you would now say >= {?StartDate} and <=
Edited by: Kyle McAdam on Aug 15, 2008 6:31 PM -
Extracting a count of distinct values between two date ranges over months
Hi All,
I am having a bit of difficulty in figuring out the query to build a list of active campaigns over a date range.
i.e. I have a table with campaign IDs and their start and end date details like this
Campaign_id Start_date End_date
10001 1-Jun-09 31-May-11
10002 1-Jun-09 23-Jun-11
30041 21-Aug-09 31-Dec-09
20005 3-Jun-10 31-May-11
90021 21-Nov-09 30-Nov-10
54000 1-Jun-11 1-Dec-12
35600 1-Mar-10 31-Mar-12 What the above data means is, for eg. the campaign 10001 is active from 1-Jun-09 to 31-May-11 i.e. for 24 months (inclusive of the month Jun-09 and May-11)
What I need to figure out is the counts of active campaigns between a date range and display that active count at a month level (for e.g. lets say we want to see all the campaigns that were active
between the date range '01-JUN-2007' and '30-APR-2012' ). So the partial output would be as seen below. The list would continue till december-2012
Month Year Count of active campaigns
Jan 2009 0
Feb 2009 0
Mar 2009 0
Apr 2009 0
May 2009 0
Jun 2009 2
Jul 2009 2
Aug 2009 3
Sep 2009 3
Oct 2009 3
Nov 2009 4
Dec 2009 4
Jan 2010 3
Feb 2010 3
Mar 2010 4
Apr 2010 4
Dec 2012 1 Could anybody please help me with the right query for this.
Thanks a lot for help
Regards
Goldiset pagesize 40
with tab as
select 1 id, sysdate -100 start_date, sysdate end_date from dual
union
select 1 id, sysdate -200 start_date, sysdate -150 end_date from dual
union
select 1 id, sysdate -600 start_date, sysdate - 400 end_date from dual
union
select 1 id, sysdate -300 start_date, sysdate - 150 end_date from dual
union
select 2 id, sysdate -100 start_date, sysdate-50 end_date from dual
year_tab as
select
add_months(min_date, level -1) m
from
select min(trunc(start_date,'YYYY')) min_date, add_months(max(trunc(end_date,'YYYY')), 12) max_date
from tab
connect by level <= months_between(max_date, min_date)
select to_char(m,'YYYY') year_,
to_char(m,'Month') month_,
nvl(act, 0) act
from year_tab,
select m date_,count(*) act
from tab, year_tab
where m between trunc(start_date,'MM') and trunc(end_date,'MM')
group by m
) month_tab
where m = date_(+)
order by m;
YEAR_ MONTH_ ACT
2010 January 0
2010 February 0
2010 March 0
2010 April 0
2010 May 0
2010 June 0
2010 July 0
2010 August 0
2010 September 1
2010 October 1
2010 November 1
2010 December 1
2011 January 1
2011 February 1
2011 March 1
2011 April 0
2011 May 0
2011 June 0
2011 July 1
2011 August 1
2011 September 1
2011 October 2
2011 November 2
2011 December 2
2012 January 2
2012 February 2
2012 March 2
2012 April 1
2012 May 1
2012 June 0
2012 July 0
2012 August 0
2012 September 0
2012 October 0
2012 November 0
2012 December 0
36 rows selected. -
Need to fetch value from a table based on data range
Hello there,
I was hoping that the community could give me a hand with this little puzzle I got.
I am currently creating a Time Dimension for a data wharehouse, and I have the requirement to populate a column named SEASON (e.g: Summer, Winter, Spring, Autumn) for each date row. So for the 20/Dec/2013, the Season column must say Winter.
Here is now my Time Dimension table looks like, without the Season information (which I yet have to load):
DimTime Table
TIMEID
FULLDATE
YEAR
SEASON
MONTH
MONTHDAY
WEEK
WEEKDAY
274
02-MAR-10
2010
3
2
9
2
275
03-MAR-10
2010
3
3
9
3
276
04-MAR-10
2010
3
4
9
4
277
05-MAR-10
2010
3
5
9
5
278
06-MAR-10
2010
3
6
9
6
279
07-MAR-10
2010
3
7
9
7
This entire table is being populated using Oracle functions to manipulate a date field from another table, named PDATE:
My ETL Code
INSERT INTO DimTime(timeid, fulldate, year, month, monthday, week, weekday)
SELECT tim_seq.NEXTVAL, pdate, year, month, monthday, week, weekday
FROM (SELECT DISTINCT pdate, EXTRACT(year from pdate) year, EXTRACT(month from pdate) month,
EXTRACT(day FROM pdate) monthday, to_number(to_char(to_date(pdate,'DD/MM/YY'),'IW')) week,
TO_CHAR(pdate, 'D') weekday
FROM Performance PER
ORDER BY pdate);
NOTE: Code considers the table DimTime to be truncated every time it loads (i.e.: I don't need to consider additional loads).
As you can see, Season wasn't populated. Since the solstices and equinoxes vary for each year, I can't just say that Summer start at a given date (e.g: 21 of June) because one year it could be the 19/Jun, another the 22/Jun, etc. So in order to solve this problem, I have a table named Season which defines the START and END dates for the seasons:
Season Table
SEASON#
SEASONNAME
YEAR
DATEFROM
DATETO
1
Spring
2010
01-MAR-10
30-MAY-10
2
Summer
2010
31-MAY-10
29-AUG-10
3
Autumn
2010
30-AUG-10
28-NOV-10
4
Winter
2010
29-NOV-10
27-FEB-11
5
Spring
2011
28-FEB-11
29-MAY-11
6
Summer
2011
30-MAY-11
28-AUG-11
7
Autumn
2011
29-AUG-11
27-NOV-11
8
Winter
2011
28-NOV-11
26-FEB-12
9
Winter
2009
30-NOV-09
28-FEB-10
This is the bit I don't know how to do. How can I make sure that I populate the correct Season in my DimTime table based on the season specified in the Season table?
Thanks in advance for your help!
Regards,
P.Just join to table Season:
INSERT
INTO DimTime(
timeid,
fulldate,
year,
month,
monthday,
week,
weekday,
seasonname
SELECT tim_seq.NEXTVAL,
pdate,
year,
month,
monthday,
week,
weekday
FROM (
SELECT DISTINCT pdate,
EXTRACT(year from pdate) year,
EXTRACT(month from pdate) month,
EXTRACT(day FROM pdate) monthday,
to_number(to_char(to_date(pdate,'DD/MM/YY'),'IW')) week,
TO_CHAR(pdate,'D') weekday,
seasonname
FROM Performance PER,
season
WHERE pdate between datefrom and dateto
SY. -
How to use bind variale to create list of values? show date range?
Hi,
Dose anybode have a way to get around "bind variables are not allowed in Select statement" when create list of values from select? I have to create this based on who the user (one parameter passed into report) is.
Another Question:
I like to current date and current date-30 days on my report, how to achieve this?
Any help wil be greately appreciated.
ThanksHi LC...
Your approach is good...
but i said to change the column formula not in criteria...
but i wanted to done this change in fx of Dashboard prompt (presentation variable) column...
Of course i appreciate your approach... it was simple ...
Thanks & Regards
Kishore Guggilla
KUSHALINC -
Filter value based on Date in OBIEE 11g, Reporting Issue
Hi,
I have following tables
Dim_Item
Dim_Loc
Fact_Price-Item_Key,Loc_Key,Date_Key,Reason_Code,Amount,Load_date
Reason Code is the code which discribes the reson behind price change
Amount- price of Item at particular location (Note: one item can have different price at different location)
Load Date - When ever there is price change for a particular item at particular location new record is inserted in the fact load date represents the date on which the data is updated
Item_key Loc_key Date_key Reason_Code Amount Load_Date
1 1 20131113 0 1400 13/11/2013
1 1 20131115 6 1100 15/11/2013
2 1 20131112 0 900 12/11/2013
2 2 20131112 0 1200 12/11/2013
2 2 20131113 3 325 13/11/2013
My report requirement is
Report should show only the Item & location for which there is price change
Report should be like
Item Loc Orignal_Amt Changed_Amt
1 1 1400 1100
2 2 1200 325
I have tried to calculate Orignal_Amt by taking Min(Load_Date) & Changed_Amt by taking Max(Load_Date) but result is not correct
I need to min(Load_Date) or max(load_date) for an Item at particular location
i.e it should be like min(load_date by item_key,loc_key)
max(load_date by item_key,loc_key)
then I can filter out Amount based on this min & max value.
How can I achive this, is there any other approach to achive this
Thanks
SameerHi,
Does this approach with comparing prices in the first and last date of the period actually indicates the price change?
What about the sample data below - is considered to be a price change or not?
Item_key Loc_key Date_key Reason_Code Amount Load_Date
2 2 20131110 0 325 12/11/2013
2 2 20131111 0 1100 12/11/2013
2 2 20131112 0 1200 12/11/2013
2 2 20131113 3 325 13/11/2013
Option #1:
Use 2 requests:
Req1 selects surrogate key for the first and last record by load date for each location and product. Surrogate key is just a concatenated expression of Item_Key, Loc_Key and Load_Date fields (use separators between them).
For this request you need to filter out all other dates but first and last - use Rank function with BY clause. It will be 2 calculated fields: RANK(Date_Load BY Item_Key, Loc_Key) = last date, RANK(-Date_Load BY Item_Key, Loc_Key) = first date. Select records having any of these ranks=1.
In result this request should return up to 2 records for each product-location combination with surrogate key, something like this for my example:
Item_key Loc_key Date_key Reason_Code Amount Load_Date KEY
2 2 20131110 0 325 12/11/2013 LOC:2;ITM:2;DT:20131110
2 2 20131113 3 325 13/11/2013 LOC:2;ITM:2;DT:20131113
In fact, it could be more than 2 records in case there are more than 1 change in a day for the price and no time stored on date field. This is up to you how to eliminate duplicates.
Now you have another request, resulting one, which is filtered by Req1 using the same surrogate key expression. Orignal_Amt =Min(Amount), Change_Amt = Max(Amount). Apply a filter to find records with different values between them.
In result, if product price is the same in the beginning and end of period (or it is single record) - these records will be filtered out, otherwise you get them in the report.
Option #2:
Play around with logical SQL under Advanced tab, it allows you to write requests with joins (as regular SQL does).
This is sort of desperate option as such an analysis is hard to maintain (make modifications to it).
Maybe you are looking for
-
New Tab opens to random websites every 15 minutes
Here are the details of the random tab that opens every 15 minutes. Application Basics Name: Firefox Version: 31.0 User Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0 Crash Reports for the Last 3 Days All Crash Report
-
How can you create a layer under a table?
If anyone knows how- or can send me a linkon how to create a layer under a table. Great help!! ty
-
Hi, I bought a T420 partly because it seemed to have great power options. I intend to use the laptop on a sailing boat. At times, I need to run power hungry CAD software, and the machine does that just fine. When I'm at sea, I need the laptop to run
-
Time Warner Cable - Can They Recall Collection??
Hi all, I've been working to get a $500 collection removed from credit report from Time Warner. It is now with Collection Bureau of America (CBA). I sent CBA a PFD - They didn't respond I then decided to call Time Warner to see if they cou
-
Cannot get back to original screen
I have trouble accessing the Cablevision.com website under Firefox and I don't have this problem with I.E. I have seen this problem only on this one website. I have tried this using my Windows 7 laptop and my two XP computers. The problem is that it