Hierarchy query with dynamic start condition
Hi,
I have a table that stores hierarchical items (foohierarchy) and another one storing users and such items (useritems). Unfortunately the latter one is not consistent and misses some entries. I would like to fix that using pure sql. Fixing here means that a user that possesses a certain child element should also have parents of that child. There are a couple of obstacles here though. First the hierarchy table does not explicitly state which elements are top level elements. I am trying to fix that by emulating a proper structure and named that fixedhierarchy. A select statement that returns all intended user/item relationships would be nice.
Here some visualization and sample data, the sample data follows the pattern that each item uses its level as its suffix, but this shouldn't be exploited in the statement:
asci art:
-- A1 (peter,paul)
-- \_ B2
-- \_ C2
-- \_D3 (thomas)
-- \_X4
-- E1
-- \_F2
-- G1
-- \_H2 (heidi)sample data
drop table foohierarchy;
drop table useritems;
create table foohierarchy (
child_item varchar2(30),
parent_item varchar2(30));
insert into foohierarchy values ('B2','A1');
insert into foohierarchy values ('C2','A1');
insert into foohierarchy values ('D3','C2');
insert into foohierarchy values ('X4','D3');
insert into foohierarchy values ('F2','E1');
insert into foohierarchy values ('H2','G1');
create table useritems (
username varchar2 (40),
item varchar2(30)
insert into useritems values ('peter','A1');
insert into useritems values ('paul','A1');
insert into useritems values ('thomas','D3');
insert into useritems values ('heidi','H2');
commit;my attempt at fixing the hierarchy table
with fixedhierarchy as
(select parent_item,child_item from foohierarchy
union all
select distinct null parent_item,parent_item child_item from foohierarchy where parent_item not in (select child_item from foohierarchy))
select * from fixedhierarchy;What the select should return:
'peter'|'A1'
'paul'|'A1'
'thomas'|'A1'
'thomas'|'C2'
'thomas'|'D3'
'heidi'|'G1'
'heidi'|'H2'
Hi,
Thanks for posting the CREATE TABLE and INSERT statments; that's very helpful! Don't forget to mention what version of Oracle you're using. That's especially important with hierachies; every version since Oracle 7 has had significant improvements in how to handle them.
I'm a little comfused as to what you want. Are you trying to permanently change the tables? If so, show what the changed table(s) should look like when the job is finished. Post the output you would want to see from "SELECT * FROM useritems;" or "SELECT * FROM foohierarchy;", or, if you want to change both tables, from both.
It looks like you have two separate problems:
(1) Changing foohierarchy, so that every item appears once as a child_id. That means adding rows with NULL parent_item for all the roots ('A1', 'E1' and 'G1'). The query you posted seems directed toward this.
(2) Denormalizing useritems, so that when a username is linked to an item, the username is linked to all that item's ancestors, too. The results you posted seem to be what you want useritems to look like after this is done.
Here's how to do those things:
<h4>(1) Changing foohierarchy</h4>
The query you posted looks good. Do you see anything wrong with it? You can use that query (or something very close to it) in an INSERT or MERGE statement.
If you just want to add some new rows to foohierarchy, then you don't need the UNION: just the second branch of it. If you're cvertain that none of those rows already exist in foohierarchy, then
INSERT INTO foohierarchy (parent_item, child_item)
SELECT DISTINCT NULL, childitem
FROM foohierarchy
WHERE parent_item NOT IN (
SELECT child_item
FROM foohierarchy
;If some of the roots might already be in foohierarchy correctly, then you'll want a something in the WHERE clause to make sure you don';t add a duplicate. A MERGE statment might do this better than INSERT.
<h4>(2) Denormalizing useritems</h4>
This adds new rows to useritems, to make it look like what you posted:
ERGE INTO useritems dst
USING (
WITH all_ancestors AS
SELECT CONNECT_BY_ROOT child_item AS descendant
, parent_item AS ancestor
FROM foohierarchy
START WITH child_item IN (
SELECT item
FROM useritems
CONNECT BY child_item = PRIOR parent_item
SELECT DISTINCT
u.username
, a.ancestor
FROM all_ancestors a
JOIN useritems u ON a.descendant = u.item
) src
ON ( src.username = dst.username
AND src.ancestor = dst.item
WHEN NOT MATCHED THEN
INSERT (dst.username, dst.item)
VALUES (src.username, src.ancestor)
;After doing this, "SELECT * FROM useritems;" will produce this output:
USERNAME ITEM
paul A1
peter A1
thomas A1
thomas C2
thomas D3
heidi G1
heidi H2Here's how it works:
Sub-query all_ancestors is a bottom-up CONNECT BY query, linking each node in useritems with all of its ancestors. CONNECT BY queries are often slow under the best circumstances; doing a join in a CONNECT BY query makes it even slower. It's more efficient to do the CONNECT BY query first, in a sub-query, and then join tht result set to other tables, as I did in src.
Similar Messages
-
Dynamic select query with dynamic where condition
Hi all,
I want to use the dynamic select query with dynamic where condition. For that I used the below code but I am getting dump when using this code.
Please advice, if there is any other way to achieve this requirement.
Thanks,
Sanket Sethi
Code***************
PARAMETERS: p_tabnam TYPE tabname,
p_selfl1 TYPE edpline,
p_value TYPE edpline,
p_where1 TYPE edpline .
DATA: lt_where TYPE TABLE OF edpline,
lt_sel_list TYPE TABLE OF edpline,
l_wa_name TYPE string,
ls_where TYPE edpline,
l_having TYPE string,
dref TYPE REF TO data,
itab_type TYPE REF TO cl_abap_tabledescr,
struct_type TYPE REF TO cl_abap_structdescr,
elem_type TYPE REF TO cl_abap_elemdescr,
comp_tab TYPE cl_abap_structdescr=>component_table,
comp_fld TYPE cl_abap_structdescr=>component.
TYPES: f_count TYPE i.
FIELD-SYMBOLS : <lt_outtab> TYPE ANY TABLE,
* <ls_outtab> TYPE ANY,
<l_fld> TYPE ANY.
struct_type ?= cl_abap_typedescr=>describe_by_name( p_tabnam ).
elem_type ?= cl_abap_elemdescr=>describe_by_name( 'F_COUNT' ).
comp_tab = struct_type->get_components( ).
comp_fld-name = 'F_COUNT'.
comp_fld-type = elem_type.
APPEND comp_fld TO comp_tab.
struct_type = cl_abap_structdescr=>create( comp_tab ).
itab_type = cl_abap_tabledescr=>create( struct_type ).
l_wa_name = 'l_WA'.
CREATE DATA dref TYPE HANDLE itab_type.
ASSIGN dref->* TO <lt_outtab>.
*CREATE DATA dref TYPE HANDLE struct_type.
*ASSIGN dref->* TO <ls_outtab>.
* Creation of the selection fields
APPEND p_selfl1 TO lt_sel_list.
APPEND 'COUNT(*) AS F_COUNT' TO lt_sel_list.
** Creation of the "where" clause
*CONCATENATE p_selfl1 '= '' p_value ''.'
* INTO ls_where
* SEPARATED BY space.
*APPEND ls_where TO lt_where.
* Creation of the "where" clause
APPEND p_where1 TO lt_where.
* Creation of the "having" clause
l_having = 'count(*) >= 1'.
* THE dynamic select
SELECT (lt_sel_list)
FROM (p_tabnam)
INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>.
* WHERE (lt_where).Hi Sanket,
The above given logic of mine works for you, put the code in the If condition and try-
just like below:
IF NOT P_EBELN IS INITIAL.
lt_where = '& = ''&'' '.
REPLACE '&' WITH p_ebeln INTO lt_where.
REPLACE '&' WITH field_value INTO lt_where.
SELECT (lt_sel_list) INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>
FROM (p_tabnam)
WHERE (lt_where).
ENDIF.
thanks\
Mahesh -
Absolute dynamic select query with dynamic join and where
Has anyone ever tried creating an absolutely dynamic SELECT query with dynamic Join and Where conditions.
I have a requirement of creating such a query in an Utility Class, and i have written the code. But its throwing my sysntax errors.
Please let me know where am I going wrong OR is it really possible to create such a dynamic Query??
SELECT (FIELDS) INTO TABLE IT_TABLES
FROM ( (ME->TABLE1) inner join ( me->table2 )
on ( on_condition ) )
WHERE (me->where_fields).
Ags.It worked for me in a following way:
select * into corresponding fields of table <result_table>
from (join_string)
where (l_where).
Where the contents of join_string were dynamically build using concatenation. So it will be something like
concatenate ME->TABLE1 'as a INNER JOIN' me->table2 'as b ON (' into join_string separated by space.
<...>
add here matching/reference colums, something like
concatenate 'a~' me->TABLE1_JOIN_COL into temp1.
concatenate 'b~' me->TABLE2_JOIN_COL into temp2.
concatenate join_string temp1 '=' temp2 into join_string separated by space.
<...>
concatenate join_string ')' into join_string separated by space.
And then use similar approach for l_where variable. -
Running a SQL Stored Procedure from Power Query with Dynamic Parameters
Hi,
I want to execute a stored procedure from Power Query with dynamic parameters.
In normal process, query will look like below in Power Query. Here the value 'Dileep' is passed as a parameter value to SP.
Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData 'Dileep'"]
Now I want to pass the value dynamically taking from excel sheet. I can get the required excel cell value in a variable but unable to pass it to query.
Name_Parameter = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
Name_Value = Name_Parameter{0}[Value],
I have tried like below but it is not working.
Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData Name_Value"]
Can anyone please help me with this issue.
Thanks
DileepHi,
I got it. Below is the correct syntax.
Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData '" & Name_Value & "'"]
Thanks
Dileep -
Creating Query with dynamic columns to show results
Hi experts,
I need to know how to create a query with dynamic columns. Meaning, I don't want to create a query with fixed columns representing the 12 periods of the fiscal year to show me actuals as the fiscal year proceeds.
For example, if I am currently in the middle of period 3 (March) of a fiscal year, when I execute the query, I need it to automatically only show me the 'Actuals' for periods 1 and 2, without seeing the columns from periods 3 to 12 showing blank.
Then when I am in the middle period 5 (May) the query should ONLY show me the columns for periods 1 to 4 'Actuals', no results should be shown for periods 5 to 12 yet, and I don't want to even see blank columns for period 6 to 12.
How do I define my columns, to achieve this.
Maximum points will be awarded.
Thanks Everyone.Hi Josh,
I'm having a little difficuluty understanding what should be included in my restricted key figures.
The time characteristics that I have available to use are:
0FISCPER3 (posting period)
0FISCYEAR (fiscal year), currently using SAP EXIT to default current fiscal year.
0FISCVARNT (fiscal year variant).
In addition, I have the following characteristics available to be used in the columns:
Value type (10)
version (currently I'm using variable for it)
Currency type (020)
Currency (USD).
Can you explain what my restricted key figure should be based on and how it should look.
I tried to create a restircted key figure using 0AMOUNT, and 0FISCPER3. For 0FISCPER3 I created a range from 1 to previous period (using SAP EXIT that supplied previous period).I also had value type, version, currency type, and currency included in that restricted key figure.Then when I tried to drag 0FISCPER3 under the restricted key figure once again, it wouldn't let me, probably because I've already used 0FISCPER3 in the restricted key figure.
Please let me know if my explanation is not clear.
Your step by step help would be great.
Thanks
Edited by: Ehab Mansour on Sep 23, 2008 2:40 PM -
Sql query with dynamic fiscal year
Hi,
I wrote this query with static fiscal year and fiscal period, I need info on making the variables dynamic
Fiscal year : starts from July1st. So this year until June'30 it is '2011' and from July'1st its '2012'
Fiscal period: July1st its '1' and June'1st its '12'
Query:
select distinct o.c_num, o.ac_num, s.sub_ac_num, o.fiscal_year, o.ac_exp_date, s.sub_ac_ind
from org_account o
left outer join sub_account s
on o.c_num = s.c_num and o.ac_num = s.ac_num
where (o.ac_exp_date >= CURRENT_DATE or o.ac_exp_date is null)
and o.fiscal_year = *'2011'* --> need to be dynamic
and o.fiscal_period = *'12'* --> need to be dynamic
thanks,
Mano
Edited by: user9332645 on Jun 2, 2011 6:55 PMHi, Mano,
Welcome to the forum!
Whenever you have a question, please post a little sample data (CREATE TABLE and INSERT statements), and the results you want from that data.
Always say which version of Oracle you're using.
Since this is your first thread, I'll post some sample data for you:
CREATE TABLE table_x
( dt DATE
INSERT INTO table_x (dt) VALUES (DATE '2010-12-31');
INSERT INTO table_x (dt) VALUES (DATE '2011-01-01');
INSERT INTO table_x (dt) VALUES (DATE '2011-06-02');
INSERT INTO table_x (dt) VALUES (DATE '2011-06-30');
INSERT INTO table_x (dt) VALUES (DATE '2011-07-01');Is this the output you would want from that data?
DT FISCAL_YEAR FISCAL_PERIOD
31-Dec-2010 2011 06
01-Jan-2011 2011 07
02-Jun-2011 2011 12
30-Jun-2011 2011 12
01-Jul-2011 2012 01If so, here's one way to get it:
SELECT dt
, TO_CHAR ( ADD_MONTHS (dt, 6)
, 'YYYY'
) AS fiscal_year
, TO_CHAR ( ADD_MONTHS (dt, 6)
, 'MM'
) AS fiscal_period
FROM table_x
ORDER BY dt
;Since your fiscal year starts 6 months before the calendar year, you need to add 6 months to the actual date to get the fiscal year and month.
The query above produces strings for fiscal_year and fiscal_period. If you'd rather have NUMBERs, then use EXTRACT instead of TO_CHAR:
SELECT dt
, EXTRACT ( YEAR
FROM ADD_MONTHS (dt, 6)
) AS fiscal_year
, EXTRACT ( MONTH
FROM ADD_MONTHS (dt, 6)
) AS fiscal_period
FROM table_x
ORDER BY dt
;The first query will work in Oracle 6 (and higher).
I'm not sure when EXTRACT was introduced. It definitely works in Oracle 10, and may be available in earlier versions, too. -
Add "cost center" query to a start condition?
Hi there,
we got a new requirement for one of our plants.
We're on SRM 5.0 classic scenario.
Is it possible to add a "cost center" query to a specific start condition (SWB_PROCUREMENT) of a workflow?
E.g. if a user uses cost center 4711 for a shopping cart item a specific cost center responsible xyz should approve this item.
If the user uses another cost center 4712 for a second item in this shopping cart this item should be approved by another cost center responsible abc.
Is that somehow possible ?
So far I did not find a suitable expression for cost center.
Thanks in advance for your answers.
Best regards,
HenningHi Masa,
thanks for your answer. Perhaps you also have a hint for the following:
I can't really find in the metioned thread or in note 731637 what happens if a SC with several items is partially approved.
Example:
SC with 3 items:
item 1 cc 1000
item 2 cc 2000
item 3 cc 1000
Let's say item 1+3 have been approved by the approver found by badi and WS14500015. Is a PO or a purchase requisition created in backend? Or is it only created after the whole SC has been approved (i.e. also item 2).
Thanks for a hint and best regards,
Henning -
Input query with dynamic actual & forecast values by month per year
Hello,
I am working on a Input ready query for a forecasting application which shows both actuals and forecast numbers and the user will revise the forecast numbers by month
Requirement: I want to build a Input query for monthly forecasting for the current year. It will be dynamic rolling of months with actuals & forecast data.
E.g. My report has 12 months for the current year
and if run the report in May, the months before May has to show the actuals and the months after May has to show the old forecast data so that the user will revise the numbers again in each month and save the data to the real time cube.
Jan.Feb.Mar.Apr.May.Jun.Jul.Aug.Sept.Nov.Dec
Act Act Act Act Act Old frcst for the remaining months
user will revise forecast for these months
So, i am able to create Input query with all restricted key figures( plan kf has change mode set to change, actual kf are not set change) and calculate key figures and all the logic is done on dynamically moving/rolling the data based on the input month of the year.
But the problem is that i am using cal kf to dynamically roll months, i was not able to set the change option for the cal kf.
So, how can i make sure that the dynamically changed plan months will open for entering forecast and the actuals months not to change?
Do you guys have any better solutions in implementing it?
I really appreciate it your input....:)
Thanks,
SriniHi,
Please look at the following DOC which may be useful to you and if so please grant me point.
Regards,
SUbha'
Input-Ready Query
Use
You use input-ready queries to create applications for manual planning. These can range from simple data entry scenarios to complex planning applications.
Integration
You define a query that you want to use for manual planning in the BEx Query Designer (see Defining New Queries).
In the Web Application Designer or the BEx Analyzer, you can combine the input-ready queries with other queries and planning functions to create complex planning applications.
Prerequisites
You can define an input-ready query on any of the following InfoProviders:
● Aggregation levels (see Aggregation Levels)
● MultiProviders that include at least one simple aggregation level
The aggregation levels are created in the planning modeler; MultiProviders are defined in the modeling functional area of the Data Warehousing Workbench.
Features
Definition of an Input-Ready Query
Once you have defined a query on an InfoProvider, you see the Planning tab page under the Properties of structural components (for example, in key figures or restricted key figures). The options provided there allow you to determine which structural components of an input-ready query are to be input ready at runtime and which are not. With structural components that are not input ready, you can also determine whether these components are viewed as reference data or are just protected against manual entry.
For the structural components, you also have the following options:
Input readiness of structural components of a query
Option
Description
Not input ready (reference data)
If they are being used as reference data, the structural components are not protected by data locks to ensure exclusive access for one user because this data serves as a reference for many users.
This is the default setting.
Not input ready (no reference data)
If you want to protect structural components against manual entries but allow changes by planning functions, you can use locks to protect this data for one particular user. In this way you can ensure that the planning function works with the displayed data only and not with data that has been changed by other users.
Input ready
You can also determine whether an input ready query is to be started in change mode or in display mode. You find this property in the Query Properties on the Planning tab page. If there is at least one input-ready query component, the query (as long as it has not been determined otherwise) is started in display mode.
In BI applications that use input ready queries as data providers, you can enter data manually at runtime. For more information, see Performing Manual Planning and Creation of Planning Applications.
Example
You want to create an input-ready query for manual planning for a plan-actual comparison of revenues for a set of products. You want the plan data in a real-time-enabled InfoCube and the actual data in a standard InfoCube.
1. Create a MultiProvider that includes the InfoCubes for the plan and actual data.
2. Define an aggregation level on the MultiProvider which contains the characteristic Product and the key figure Revenue.
3. On the aggregation level, create two restricted key figures Plan Revenue and Actual Revenue. For restriction, choose the characteristic 0INFOPROV and restrict it to the plan or actual InfoCube.
4. Add the restricted key figures to the key figure structure. Insert Product into the rows. For Plan Revenue, choose Input Ready for the input-readiness option. For Actual Revenue, choose the option Not Input Ready (Reference Data).
5. In the query properties, set the indicator that determines whether the queries are started in display or change mode as required.
Example of an input-ready query
Product
Plan Revenue
Actual Revenue
P01
20
P02
30
If you want to keep actual and plan data in a real-time enabled InfoCube, you do not require a MultiProvider for the task described above. Create an aggregation level on the InfoCube and define the input-ready query for the aggregation level. In the example above, a version characteristic acts as the InfoProvider. Create restricted key figures with the plan or actual version and proceed as in the previous example. -
Issue with Dynamic WHERE condition in Cursor in FUNCTION.
Hi All,
I am facing an issue with cursor having dynamic WHERE condition in a function.
Below is the FUNCTION:
CREATE OR REPLACE FUNCTION EXCEPTION_MERGE(TABLE_NAME IN VARCHAR2, TAB_NAME IN VARCHAR2)
RETURN VARCHAr2
IS
stmt_tabcols VARCHAR2(32767);
v_columnname VARCHAR2(32767);
CURSOR C1 IS
SELECT 'A.'||A.COLUMN_NAME ||' = '|| 'B.'||B.COLUMN_NAME COLUMN_NAME
FROM
SELECT COLUMN_ID, COLUMN_NAME
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME = TABLE_NAME
AND COLUMN_NAME NOT IN ('ERROR_TAB_ID','ERROR_LOAD_DATE')
) A,
SELECT COLUMN_ID, COLUMN_NAME
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME = TAB_NAME
) B
WHERE A.COLUMN_ID = B.COLUMN_ID;
BEGIN
FOR TABCOL IN C1
LOOP
stmt_tabcols := stmt_tabcols ||TABCOL.COLUMN_NAME||',';
END LOOP;
stmt_tabcols := RTRIM(stmt_tabcols, ',');
RETURN stmt_tabcols;
END;
SELECT EXCEPTION_MERGE('WC_W_TEST_FS','WC_W_TEST_FS_GBL') FROM DUAL;It throws, below error:
ORA-06502 : PL/SQL : Numeric or value error : character string buffer too smallIf I REPLACE TABLE_NAME and TAB_NAME with hard coded values , it works fine. Can somebody look at the code and let me know the issue.
Edited by: ace_friends22 on Sep 9, 2012 1:08 PMEtbin neatly demonstrating the value of posting code in a manner which makes it easy to read.
It's obviously an naming/scoping issue. Faced with a join like this:
where table_name = table_namethe engine looks for something called table_name in the current scope. It finds it, a column on USER_TAB_COLUMNS and applies it to both sides of the filter. It has no way of knowing that there is also a parameter called TABLE_NAME, because that is outside its current scope. Consequently the query will join every table in your schema regardless of what values you pass, and that's why you blow the buffer.
Takw etbin's advice and name your parameter with a prefix:
where table_name = p_table_nameThis isn't a column in USER_TAB_COLUMNS which will force the engine to look in the next scope up, which in your case is the function, where it will find your parameter and so generate a query for the passed values only.
Cheers, APC
Edited by: APC on Sep 9, 2012 8:03 AM -
Hello,
I would like to create a Dynamic SQL in which change is the name of the table according to the outcome of the first SQL. This is possible?
'WITH TABLE_X AS(SELECT LEVEL LVL FROM DUAL CONNECT BY LEVEL <= 12)' ||
'SELECT A.COL1, A.COL2, B.COL1, B.COL7' ||
' FROM TABLE_A' || TABLE_X.LVL || ' A' ||
' , TABLE_B' || TABLE_X.LVL || ' B' ||
' WHERE A.COL1 = B.COL1 AND ... 'tables in database
TABLE_A1
TABLE_A2
TABLE_A12
TABLE_B1
TABLE_B2
TABLE_B12let me know how I can do this
RegardsHi,
Sorry, I don't see what you're trying to do.
"Dynamic SQL" is really a mis-nomer. The number of tables and columns in a query, and their names, must be spelled out when the statement is compiled. There is nothing dynamic about it.
In dynamic SQL, a PL/SQL procedure or another query writes all or part of query just milliseconds before it is compiled, typically using data taken from tables or supplied by a user right then.
For example, consider this static query:
SELECT a.col1, a.col2, b.col1, b.col7
FROM table_1 a
, table_2 b
WHERE a.col1 = b.col1;Now, say the 1 in "table_1" and the 2 in "table_2" are variables, x and y, that you will want to look up from another table every time you run this query. You can make it dynamic like this:
sql_txt := 'SELECT a.col1, a.col2, b.col1, b.col7 '
|| 'FROM table_' || TO_CHAR (x) || ' a '
|| ', table_' || TO_CHAR (y) || ' b '
|| 'WHERE a.col_1 = b.col1';Now let's make it really interesting. Say that instead of 2 tables, and 1 join condition, you''ll have n tables and n-1 join conditions, where n has to be computed at (actually a split second before) run-time. That is, if n=4, you might need to construct a static query with 4 tables and 3 join conditions, like this:
SELECT a.col1, a.col2, b.col1, b.col7
FROM table_1 a
, table_2 b
, table_12 c
, table_2 d
WHERE a.col1 = b.col1
AND a.col1 = c.col1
AND a.col1 = d.col1;You can do that using dynamic SQL, too.
Post an example of the static query you need to build, and describe what parts of it are dynamic, and how you get the values for those parts, and someone will help you write the dynamic SQL. -
Query with Top N Condition (Result Row)
Hi,
I made a query with an active top n condition. The query has 2 Keyfigures and 1 formula
Gross-sales acutal | Gross-sales previous year | Previous Year %
So that to result line is correct, I had to say "Calculate result as summation" for the keyfigures
gross sales actual and gross sales previous year. That works.
I have the problem with my formula. the formular for previous year % is defined as follows:
gross sales actual %A gross sales previous year
Example Top 3 Customer
gross sales actual gross sales prev. year prev. year %
Cust 1 100 80 125 %
Cust 2 90 45 200 %
Cust 3 80 60 133 %
Result 270 185 142.8 % ( 350 * 100 / 245 )
The result of 142 % is the correct result without the condition top 3. with the top 3 condition
the result should be 270 * 100 / 185 = 145.9 %
Additional customer without top 3 condition
Cust 4 50 40 125 %
Cust 5 30 20 150 %
It shows the correct result for each single line. The result in the result row is wrong. it is calculated
without taking the active condition. the formular calculates
with the total gross sales actual and the total of gross sales prev. year.
is there any solution the achieve the correct % in the result row?
thanks for your help.
PascalPascal,this is a known behavior with conditions.When you apply condition it just hide the extra rows and it does not impact the result row.So your result row actually shows the value irrespective of the condition you apply.
Now with the help of local functions like calculate result as summation you can show the correct sum after applying the condition but when you try to use that result in some calculation then it takes the original value thereby discarding the calculated value.
Same is happening in your case as well.Its taking the original value i.e 350 and not the calculated sum after condition i.e 270.
Hope this helps.
Regards,
AL -
Query with dynamic variables and customised caption
How to change the Field label when the query asking dynamic values during the execution?
for example: in where condition i want to give a country name during the query execution, but in the small window it will display as 'Name' which is a country name. i want to display it as 'Country Name' which should be more readable for the end user. How can we achieve this?
Thanks
SV ReddyHi,
Unfortunately, it is not possible to change the system field description.
Refer to this thread
Re: Parameter Display Name Reg.
Regards,
Vijay Kumar
SAP Business One Forums Team -
CAML Query with 10 AND conditions
Hello,
I need some help with a CAML query. This particular query needs to have 10 AND conditions. Quite frankly, with all the nesting it is driving me a little nuts:
What I have is:
<Query>
<Where>
<And>
<And>
<And>
<And>
<And>
<And>
<And>
<And>
<And>
<Eq><FieldRef Name='Column1' LookupId='TRUE' /><Value Type='Text'>10341</Value></Eq>
<Eq><FieldRef Name='Column2' LookupId='TRUE' /><Value Type='Text'>9539</Value></Eq>
</And>
<Eq><FieldRef Name='Column3' LookupId='TRUE' /><Value Type='Text'>183</Value></Eq>
</And>
<Eq><FieldRef Name='Column4' LookupId='TRUE' /><Value Type='Text'>35</Value></Eq>
</And>
<IsNull><FieldRef Name='Column5' /></IsNull>
</And>
<Eq><FieldRef Name='Column6' LookupId='TRUE' /><Value Type='Text'>4387</Value></Eq>
</And>
<Eq><FieldRef Name='Column7' LookupId='TRUE' /><Value Type='Text'>4204</Value></Eq>
</And>
<Eq><FieldRef Name='Column8' LookupId='TRUE' /><Value Type='Text'>36</Value></Eq>
</And>
<Eq><FieldRef Name='Column9' LookupId='TRUE' /><Value Type='Text'>213</Value></Eq>
</And>
<IsNull><FieldRef Name='Column10' /></IsNull>
</And>
</Where>
</Query>
I have added this into my ItemAdding Event Receiver as it will basically do a check for duplicate items based on the 10 columns.
If anyone can help guide me in this, it would be much appreciated. I have been using a CAML Query Builder to help.http://webcache.googleusercontent.com/search?q=cache:xji7jOxa5_EJ:aasai-sharepoint.blogspot.com/2013/02/caml-query-with-multiple-conditions.html+&cd=3&hl=en&ct=clnk&gl=in
http://stackoverflow.com/questions/6203821/caml-query-with-nested-ands-and-ors-for-multiple-fields
Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression
A AND B AND C looks like this:
<And>
A
<And>
B
C
</And>
</And>
Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):
<Where>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>John</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>John</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>John</Value>
</Eq>
</Or>
</Or>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>Doe</Value>
</Eq>
</Or>
If this helped you resolve your issue, please mark it Answered -
Need help with writing a query with dynamic FROM clause
Hi Folks,
I need help with an query that should generate the "FROM" clause dynamically.
My main query is as follows
select DT_SKEY, count(*)
from *???*
where DT_SKEY between 20110601 and 20110719
group by DT_SKEY
having count(*) = 0
order by 1; The "from" clause of the above query should be generated as below
select 'Schema_Name'||'.'||TABLE_NAME
from dba_tables
where OWNER = 'Schema_Name'Simply sticking the later query in the first query does not work.
Any pointers will be appreciated.
Thanks
rogers42Hi,
rogers42 wrote:
Hi Folks,
I need help with an query that should generate the "FROM" clause dynamically.
My main query is as follows
select DT_SKEY, count(*)
from *???*
where DT_SKEY between 20110601 and 20110719
group by DT_SKEY
having count(*) = 0
order by 1; The "from" clause of the above query should be generated as below
select 'Schema_Name'||'.'||TABLE_NAME
from dba_tables
where OWNER = 'Schema_Name'
Remember that anything inside quotes is case-sensitive. Is the owner really "Schema_Name" with a capital S and a capital N, and 8 lower-case letters?
Simply sticking the later query in the first query does not work.Right; the table name must be given when you compile the query. It's not an expression that you can generate in the query itself.
Any pointers will be appreciated.In SQL*Plus, you can do something like the query bleow.
Say you want to count the rows in scott.emp, but you're not certain that the name is emp; it could be emp_2011 or emp_august, or anything else that starts with e. (And the name could change every day, so you can't just look it up now and hard-code it in a query that you want to run in the future.)
Typically, how dynamic SQL works is that some code (such as a preliminary query) gets some of the information you need to write the query first, and you use that information in a SQL statement that is compiled and run after that. For example:
-- Preliminary Query:
COLUMN my_table_name_col NEW_VALUE my_table_name
SELECT table_name AS my_table_name_col
FROM all_tables
WHERE owner = 'SCOTT'
AND table_name LIKE 'E%';
-- Main Query:
SELECT COUNT (*) AS cnt
FROM scott.&my_table_name
;This assumes that the preliminary query will find exactly one row; that is, it assumes that SCOTT has exactly one table whose name starts with E. Could you have 0 tables in the schema, or more than 1? If so, what results would you want? Give a concrete example, preferably suing commonly available tables (like those in the SCOTT schema) so that the poepl who want to help you can re-create the problem and test their ideas.
Edited by: Frank Kulash on Aug 11, 2011 2:30 PM -
Single SQl Query with different where conditions
Experts,
I have a requirement to design a report. Here are the details
I have Report table layout
Profit center Gross sales (This Year) Gross Sales (Last Year) % change Year of Year
The Report has a selection of entering the Start Date.
I have a single table in oracle which has profit center and Gross Sales Values on daily basis.
I want to write a single sql query to calculate both Gross Sales current year and Gross Sales Last Year. I can calculate Gross Sales Current Year by putting the where condition for start date = Current Year Date which i pass through report. I want to calculate the Gross Sales Last Year in the Same query by putting the different where condition i.e start date = Last Year date based on the date input.
I dont know how to put two where conditions in single query for two different columns.
Any help will be appreciated.
Thanks in advance
Regards
Santoshinstead of changing your where clause couldn't you just determine the yearly totals from your table and then use the lag statement to get last years total?
something like this?
I just made up 10,000 days worth of sales and called it fake table it is supposed to represent a variant of the table you were describing as your base table.
with fake_table as
( select trunc(sysdate + level) the_day,
level daily_gross_sales
from dual
connect by level < 10001
select yr, year_gross_sale, lag(year_gross_sale) over (order by yr) prev_year_gross_sale,
(year_gross_sale - lag(year_gross_sale) over (order by yr))/year_gross_sale * 100 percent_change
from
(select distinct yr, year_gross_sale from
select the_day,
daily_gross_sales,
extract(year from the_day) yr,
extract(year from add_months(the_day,12)) next_yr,
sum(daily_gross_sales) over (partition by extract(year from the_day)) year_gross_sale
from fake_table
order by yr
)
Maybe you are looking for
-
How to load a text file int JEditorPane and highlight some words (Urgent !)
I want to load a text file into a JEditorPane and then highlights some keywords such as while,if and else.I am using an EditorKit in order to style the JEditorPane. I have no difficulty while giving the input through the keyboard but lots of exceptio
-
My serial number is not working
The serial number for my IWORK software is not working in my computer. It tells me it is invalid but I JUST purchased this software. I don't know what I am doing wrong. Anyone have any clue?
-
Hello, Short version: Can't seem to get out of PIO mode. Long version: Installed a (new from Tiger Direct) Samsung HM160HC, supposed to be the fastest drive that will work in my A25-S207. I did a clean install of XP Pro and SP3. Got all the relevant
-
My "keepers" file has disappeared .How can I get it back?
I used this file for anything important and it worked fine for awhile and then one day it disappeared, no explanation.Is there anything that I can do to bring it back or has this --------- program deleted it forever?
-
JDev902: how open form with empty JTable?
Background: Using the wizard I have created a number of JClient forms pulling their data from a BC-layer. However, some forms fill only very slowly because of the large number of rows of the underlying tables. Sometimes it would be better to open a f