ALL Clause with correlated sub queries

I have two Tables. emp and dep. In Employee emp_id and Name where emp_id is pk. emp_id is referencing emp_id in Department where Dep has 3 columns emp_id Dep_no and Dep_name. In Department table emp_id is PK.
Say: Employee Has these data: 1|john and 2|Elen and 3|Ron AND Department Table Has 1|10|Accounts and 2|20|IT.
I give the following Query:
SELECT * from Employee E where emp_id = ALL (select emp_id from Department D where D.emp_id = E.emp_id);
I suppose i should get 1|john . But Im getting All rows of Employee. Why is that D.emp_id = E.emp_id has no effect. Cant seem to understand the query plan too

Hi,
ramki_noubang wrote:
im using oracle 10G XE.
consider two tables manager_emp and emp_rk: see the results below.
select * from manager_emp;
EMP_ID     LAST_NAME MANAGER_ID
1     ram     3
2     raj     3
3     govi     100
100     mgr     -Once again, post CREATE TABLE and INSERT statements for the sample data.
select * from emp_rk;
ID     NAME     DPNO     SAL
1     ram     10     1000
2     jon     10     2000
3     man     10     1500
4     dan     30     5000
select * from manager_emp m
where (emp_id,last_name) *= all* (select id,name from emp_rk e
where e.id = m.emp_id and e.name = m.last_name);
EMP_ID     LAST_NAME MANAGER_ID
1     ram     3
2     raj     3
3     govi     100
100     mgr     -
i should get only:
EMP_ID     LAST_NAME MANAGER_ID
1     ram     3Think about what's happening.
The main query is just
SELECT  *
FROM    manager_emp  m
WHERE   (emp_id, last_name)   = ALL (subquery)
;The subquery is correlated to the main query; that means for each row in manager_emp, the subquery will be run to see if the main WHERE condition is TRUE or not.
Think about what happens when it's deciding whether or not to include the row
EMP_ID     LAST_NAME      MANAGER_ID
2     raj            3It will run this sub-query:
...         SELECT  id
         ,         name
         FROM    emp_rk  e
         WHERE   e.id    = 2          -- because m.emp_id = 2
         AND     e.name  = 'raj'     -- because m.last_name = 'raj'The sub-query will find 0 rows, and so the main WHERE condition will be TRUE, because "x = ALL (subquery)" is defined as TRUE when the subquery produces no rows.
If you want just the 1 row you mentioned, then one way to get it is an uncorrelated sub-query, something like this:
SELECT  *
FROM    manager_emp
WHERE   (emp_id, last_name)   IN
         SELECT  id, name
         FROM    emp_rk
;Once again: forget about "= ALL". Everybody else has, and there's a good reason.

Similar Messages

  • Trying to create table using Union All Clause with multiple Select stmts

    The purpose of the query is to get the Substring from the value for eg.
    if the value is *2 ASA* then it should come as ASA
    where as if the value is *1.5 TST* the it sholud come as TST like wise for others too.
    I am trying to execute the below written SQL stmt but getting error as:
    *"ORA-00998 must name this expression with the column alias 00998.00000 - Must name this expression with the column alias"*
    CREATE TABLE TEST_CARE AS
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =5
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =7
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =14
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3),LEN FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =7 AND old_care_lvl ='Regular'
    I want to create the table using the above given multiple select using the Union ALL clause but when trying to create run the query getting error as "ORA-00998 must name this expression with the column alias 00998.00000 - Must name this expression with the column alias"
    Please guide me how to approach to resolve this problem.
    Thanks in advance.

    When you create a table using a SELECT statement the column names are derived from the SELECT list.
    Your problem is that one of your columns is an expression that does not work as a column name SUBSTR(old_care_lvl,3)What you need to do is alias this expression and the CREATE will pick up the alias as the column name, like this:
    CREATE TABLE TEST_CARE AS
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3) column3, len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =5
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =7
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =14
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3),LEN FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =7 AND old_care_lvl ='Regular'
    );You may not like the name "column3" so use something appropriate.

  • Plain SQL Conditional WHERE Clause with two sub-selects

    Hi SQL Experts,
    I need a bit quick of help with a query.
    This is a "select" statement for an OBI repository phyiscal table source object.
    So I cant put PL/SQL or Stored Procedures in it. I just need
    to have two different conditions/selects depending on the user role (this information comes
    from the session).
    The above, does not work:
    --------------ORA00905. 00000 -  "missing keyword"
      SELECT OFFICENO FROM orgunit
      WHERE
      CASE WHEN 'SESSION_VARIABLE' LIKE '%globalmanager%' THEN  
            ASSIGNEDOFFICES =
            SELECT DISTINCT ASSIGNEDOFFICES
            FROM USERSTABLE INNER JOIN orgunit ON
            orgunit.OFFICEKEY = USERSTABLE.OFFICEKEY
            WHERE USERSTABLE.USERNAME ='VALUEOF(NQ_SESSION.USER)'
      ELSE
            OFFICENO =
            SELECT DISTINCT OFFICENO FROM USERSTABLE
            INNER JOIN orgunit ON
            orgunit.OFFICEKEY = USERSTABLE.OFFICEKEY
            WHERE USERSTABLE.USERNAME ='VALUEOF(NQ_SESSION.USER)'
      END;   
    Can anyone help?

    Hi,
    I can't tell what you want to do just by looking at code that doesn't do it. Maybe:
    SELECT  officeno
    FROM    orgunit
    WHERE   (    session_variable  LIKE '%globalmanager%'
            AND  assignedofficies  IN
                     SELECT  assignedoffices
                     FROM    usertable  u1
                     JOIN    orgunit    o1  ON o1.officekey = u1.officekey
                     WHERE   u1.username    = 'VALUEOF(NQ_SESSION.USER)'
    OR      (    NVL ( session_variable
                     )        NOT LIKE '%globalmanager%'
            AND  officeno        IN
                     SELECT  officeno
                     FROM    usertable  u2
                     JOIN    orgunit    o2  ON  o2.officekey = u2.officekey
                     WHERE   u2.username   = 'VALUEOF(NQ_SESSION.USER)'
    There might be some simpler and more efficient way, depending on your tables and your reuirements.
    The condition u2.username   = 'VALUEOF(NQ_SESSION.USER)' is almost certainly not what you really want.
    Whenever you have a question, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002#9362002

  • XMLAGG with multiple sub-queries

    Trying to produce xml data file where a set of users have many products and org units, outcome should look like:
    <TopTree>
    <User>
    <UserStatus>1</UserStatus>
    <Access>
    <AccessSetting><Product code="AAA"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="BBB"<</Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="CCC"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    </Access>
    <PersonInfo>
    <Name>
    <FirstName><![CDATA[John]]></FirstName>
    <LastName><![CDATA[Smith]]></LastName>
    </Name>
    <ContactInfo>
    <Email Label="business">[email protected]</Email>
    </ContactInfo>
    </PersonInfo>
    <Security>
    <Credentials>
    <UserName>jsmith</UserName>
    <Password>jsmith123</Password>
    </Credentials>
    <OrganizationUnits>
    <OrgUnit code="Engineering"></OrgUnit>
    <Roles>
    <UnitRole>INT_I</UnitRole>
    <UnitRole>REP_A</UnitRole>
    <UnitRole>OIT_S/UnitRole>
    </Roles>
    </OrganizationUnits>
    </Security>
    </User>
    </TopTree>
    am using the query:
    SELECT
    xmlElement("TopTree",
    xmlAgg(xmlElement("User"
    ,xmlElement("UserStatus", DECODE(users.term_date, NULL, 1, 0))
    ,xmlElement("Access"
    ,xmlAgg(xmlElement("AccessSetting"
    ,xmlElement("Product", xmlAttributes(acc.product_access as "code"))
    ,xmlForest(acc.activate_date as "ActivateDate"
    , acc.deactivate_date as "DeactivateDate")
    ,xmlElement("PersonInfo"
    ,xmlElement("Name"
    ,xmlElement("FirstName", xmlCDATA(users.first_name))
    ,xmlElement("LastName", xmlCDATA(users.last_name)))
    ,xmlElement("ContactInfo"
    ,xmlelement("Email", xmlattributes('business' as "Label"), users.email)
    ) -- end of ContactInfo
    ) -- end of PersonInfo
    ,xmlElement("Security"
    ,xmlElement("Credentials"
    ,xmlelement("UserName", users.login_key)
    ,xmlelement("Password", users.Password)
    ,xmlElement("OrganizationUnits"
    ,xmlElement("OrgUnit", xmlattributes('Engineering' as "code"))
    ,xmlElement("Roles", xmlagg(xmlElement("UnitRole", org.org_unit_role)))
    ) -- end of OrganizationUnits
    ) -- end of Security
    ) -- end of User
    ) -- end of xmlAgg User
    ) -- end of TopTree
    FROM user_data users
    ,user_access_v acc
    ,org_unit_roles_v org
    WHERE users.person_id = acc.person_id
    AND users.org_role = org.org_role
    GROUP BY DECODE(users.term_date, NULL, 1, 0)
    ,users.first_name
    ,users.last_name
    ,users.email
    ,users.login_key
    ,users.password
    but I'm getting
    <TopTree>
    <User>
    <UserStatus>1</UserStatus>
    <Access>
    <AccessSetting><Product code="AAA"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="AAA"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="AAA"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="BBB"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="BBB"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="BBB"<</Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="CCC"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="CCC"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    <AccessSetting><Product code="CCC"></Product><ActivateDate>2012-05-01</ActivateDate></AccessSetting>
    </Access>
    <PersonInfo>
    <Name>
    <FirstName><![CDATA[John]]></FirstName>
    <LastName><![CDATA[Smith]]></LastName>
    </Name>
    <ContactInfo>
    <Email Label="business">[email protected]</Email>
    </ContactInfo>
    </PersonInfo>
    <Security>
    <Credentials>
    <UserName>jsmith</UserName>
    <Password>jsmith123</Password>
    </Credentials>
    <OrganizationUnits>
    <OrgUnit code="Engineering"></OrgUnit>
    <Roles>
    <UnitRole>INT_I</UnitRole>
    <UnitRole>INT_I</UnitRole>
    <UnitRole>INT_A</UnitRole>
    <UnitRole>REP_A</UnitRole>
    <UnitRole>REP_A</UnitRole>
    <UnitRole>REP_A</UnitRole>
    <UnitRole>OIT_S/UnitRole>
    <UnitRole>OIT_S</UnitRole>
    <UnitRole>OIT_S</UnitRole>
    </Roles>
    </OrganizationUnits>
    </Security>
    </User>
    </TopTree>
    Have tried different combinations of XMLAGG but can't seem to get it to work when I have more than one sub-query

    Not tested (for obvious reasons) but instead of aggregating over a cartesian resultset, you can do a single scan of USER_DATA and get additional info from other tables using subqueries :
    SELECT
    xmlElement("TopTree",
      xmlAgg(xmlElement("User"
                  ,xmlElement("UserStatus", DECODE(users.term_date, NULL, 1, 0))
                  ,xmlElement("Access",
                       select xmlAgg(xmlElement("AccessSetting"
                                    ,xmlElement("Product", xmlAttributes(acc.product_access as "code"))
                                    ,xmlForest(acc.activate_date as "ActivateDate"
                                             , acc.deactivate_date as "DeactivateDate")
                       from user_access_v acc
                       where acc.person_id = users.person_id
                  ,xmlElement("PersonInfo"
                    ,xmlElement("Name"
                    ,xmlElement("FirstName",   xmlCDATA(users.first_name))
                    ,xmlElement("LastName",    xmlCDATA(users.last_name)))
                    ,xmlElement("ContactInfo"
                      ,xmlelement("Email", xmlattributes('business' as "Label"), users.email)
                               )  -- end of ContactInfo
                             )  -- end of PersonInfo
                  ,xmlElement("Security"
                     ,xmlElement("Credentials"
                       ,xmlelement("UserName", users.login_key)
                       ,xmlelement("Password", users.Password)
                     ,xmlElement("OrganizationUnits"
                        ,xmlElement("OrgUnit", xmlattributes('Engineering' as "code"))
                        ,xmlElement("Roles",
                             select xmlagg(xmlElement("UnitRole", org.org_unit_role))
                             from org_unit_roles_v org
                             where org.org_role = users.org_role
                         ) -- end of Roles
                                ) -- end of OrganizationUnits
                              ) -- end of Security                    
                           ) -- end of User
                ) -- end of xmlAgg User
              ) -- end of TopTree
      FROM user_data users
    ;

  • IN clause with ORDER BY clause in sub-queries

    Hello,
    We generate dynamic queries with the following statement pattern (could be many union/intersect sub-queries):
    select my_col
    from my_table
    where my_col IN
    select table_2.my_col , x_col from table_2 where x_col > 10
    UNION
    select table_3.my_col , y_col from table_3 where y_col > 20
    INTERSECT
    select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
    I know that I can do just the sub-queries w/ an ORDER BY clause as follows (as long as the 2nd parameter in the select stmts are of the same type):
    select table_2.my_col , x_col from table_2 where x_col > 10
    UNION
    select table_3.my_col , y_col from table_3 where y_col > 20
    INTERSECT
    select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
    order by 2 desc
    But my questions are:
    1. What is (if there is) the syntax that will ensure that the result set order will be that of the ordering of the sub-queries?
    Or does my SQL stmt have to have syntactically (but not semantically) change to achieve this?
    Thanks,
    Jim

    Randolf Geist wrote:
    just a minor doubt - I think it is not officially supported to have separate ORDER BYs in a compound query with set operators (e.g. UNION / UNION ALL subsets). Of course one could use inline views with NO_MERGE + NO_ELIMINATE_OBY hints, but I think the only officially supported approach is to use a single, final ORDER BY (that needs to use positional notation as far as I remember).
    Randolf,
    You're right, of course, about the separate "order by" clauses.
    Interestingly the following type of thing does work though (in 10.2.0.3, at least):
    with v1 as (
        select * from t1 where col1 = 'ABC' order by col2
    v2 as (
        select * from t1 where col1 = 'DEF' order by col2
    select * from v1
    union all
    select * from v2
    ;A quick check the execution plan suggsts that Oracle appears to be convering this to the following - even though its technically not acceptable in normal circumstances:
    select * from t1 where col1 = 'ABC' order by col2
    union all
    select * from t1 where col1 = 'DEF' order by col2
    ;Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    http://www.jlcomp.demon.co.uk
    To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
    "Science is more than a body of knowledge; it is a way of thinking"
    Carl Sagan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • With clause vs sub-queries

    db and dev 10g rel2 , hi all,
    i am trying to learn the "WITH CLAUSE" , and i do not see any difference between using it and using sub-queries .
    when i searched for this , i found that the with clause is used when You need to reference the subquery block multiple places in the query by specifying the query name , but i can not imagine an example for doing so .
    if you could provide me with an example please ? and telling me about another situations in which i could need using the "with clause" if any ?
    thanks

    >
    db and dev 10g rel2 , hi all,
    i am trying to learn the "WITH CLAUSE" , and i do not see any difference between using it and using sub-queries .
    when i searched for this , i found that the with clause is used when You need to reference the subquery block multiple places in the query by specifying the query name , but i can not imagine an example for doing so .
    if you could provide me with an example please ? and telling me about another situations in which i could need using the "with clause" if any ?
    >
    It isn't just about referencing a subquery multiple times. There are other advantages to using 'common table expressions'/'subquery factoring' also.
    Take a look at the example below. It first defines 'dept_costs' as a query block, then defines 'avg_cost' as a new query block and it references the first query block.
    Then the actual query references both query blocks just as if they are tables. And, in fact, in some circumstances Oracle will actually materialize them AS temporary tables.
    Look at how easy it is to understand the entire statement. You can focus first on the 'dept_costs' query block WITHOUT having to look at anything else. That is because the query block is self-contained; you are defining a result set. There is no 'join' or connection to any other part of the statement.
    It is easy for a developer, and for Oracle, to understand what is needed for that one piece.
    Next you can focus entirely on the 'avg_cost' query block. Since it uses the first query block just as if it were a table you can treat it as a table. That means you do NOT even need to look at the first query block to understand what the second query block is doing.
    Same with the actual query. You can analyze it by treating the two query blocks just as if they were other tables.
    Even better you can test the first query block by itself in sql*plus or other tool to confirm that it works and you can create an execution plan for it to make sure it will use an appropriate index. You can also then test the first and second query blocks together to make sure THEY have a proper execution plan.
    Then when you test then entire statement you already know that the query blocks work correctly.
    Try to do THAT with a query that uses nested sub-queries.
    Sure - you could write a set of nested sub-queries to accomplish the same thing (Oracle will sometimes rewrite your query that way itself) but it becomes one big query and the individual pieces are not nearly as easy to see, analyze or understand.
    It can be difficult if not impossible to extract a nested query in order to test it even to just try to get the syntax working. And when you do extract it you will often be testing something that isn't quite exactly the same as when i t was nested.
    So: easier to understand, easier to write and test (especially for new developers) as well as easier to use multiple times without having to duplicate it.
    >
    subquery_factoring_clause
    The WITH query_name clause lets you assign a name to a subquery block. You can then reference the subquery block multiple places in the query by specifying the query name. Oracle Database optimizes the query by treating the query name as either an inline view or as a temporary table.
    >
    The SQL Language doc has an example.
    http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#i2129904
    >
    Subquery Factoring: Example The following statement creates the query names dept_costs and avg_cost for the initial query block containing a join, and then uses the query names in the body of the main query.
    WITH
    dept_costs AS (
    SELECT department_name, SUM(salary) dept_total
    FROM employees e, departments d
    WHERE e.department_id = d.department_id
    GROUP BY department_name),
    avg_cost AS (
    SELECT SUM(dept_total)/COUNT(*) avg
    FROM dept_costs)
    SELECT * FROM dept_costs
    WHERE dept_total >
    (SELECT avg FROM avg_cost)
    ORDER BY department_name;
    DEPARTMENT_NAME DEPT_TOTAL
    Sales 313800
    Shipping 156400

  • SSRS subreport with a sub-report as header on all pages

    Hello,
    I need some guidance on how to get a sub-report with a sub-report header and an expanding table. Please see below.
    This is the structure of things that I have:
    Main Report 1 is being invoked by ONLY Parameter 1 (User Text Box Entry).
    It Contains:
         Page 1: Sub-Report 1 invoked by Parameter 1
         Page 2 or more Pages: Sub-report 2 and a table (T1) expanding vertically based on Parameter 1 and Parameter 2. The Sub-report 2 should appear as header on all pages where T1 rows are there. Additionally, multiple Parameter 2
    values may be present and if so, they need to appear on a different page with appropriate header/table data. Parameter 1 and 2 are associated with a ONE dataset & its fields.
         Last Page: Sub-Report 3 and few text boxes below it. Invoked by Parameter 1
    The issue is I don't know how to insert Page 2 content. I tried making a new report with Sub-report 2 and the T1 below it. This is working fine but I'm not able to get the sub-report as header on all pages EXCEPT the first page. FixedData and RepeatOnNewPage
    properties are TRUE & KEEPwithGroup is set to 'AFTER'. Also, once I'm done with this report how do I insert it in the main report. Would it be in group / outside group in the group properties -- I would really appreciate if you can guide me with steps.
    Thank you,
    Nichesl
    Nichesl

    Thanks Asha ,
    Actually this is how my Report  layout is
    Group Header
    ---Detail1
    ---Detail2
    ---Detail3
    Group Footer1 (New Page After and Show at Bottom Setting)
    Group Footer 2 (New Page Before Setting)
    This is the layout of my report.
    When Details and Group Footer1 come in same page then my Group Header works perfect.
    When there are many details then the Group Footer1 skips into next page and Group Header does not show up in that page.
    Our requirement is such a way that Group Footer1 should have Group Header and Group Footer2 should always come in new page (i.e. last Page)
    I think I made it clear on my issue/requirement.
    Again I really appreciate for your reply.
    Regards
    Kalyan

  • A Single query with out the sub-queries

    I am using My-SQL as my back-end and it doesnot support the
    Sub-Queries. i have my table given below
    UserID..UserName..ParentUserID
    1........Admin...........0
    2........Sales...........1
    3........Sourcing........1
    4........SalesHead.......2
    5........SourcingHead....3
    6........SalesExec.......4
    7........SourExec........5
    The table contains heirarchy of users. The top most users
    has the ParentUserID as 0. and the remaining has their own ParentUserID
    I want to get the complete heirarchy of a given user in single ResultSet.
    It should be done without using sub-queries. but all joins can be used.
    e.g.
    if i say userid is 2 i should get following output:
    Sales - > SalesHead -> SalesExec->......
    Can any body please help me out!
    Sridhar.

    Hi Sridhar,
    You can use recursive method. Make a method as follows :
    public String getChildren(int UserID)
         String temp = "";
         Connection con = DriverManager.getConnection("","","");
         Statement st = con.createStatement();
         ResultSet rs = statement.executeQuery("select UserID from MyUsers where ParentUserID = " + UserID);
         while(rs.next())
              temp += " [ ";
              if(temp.equals(""))
                   temp += getChildren(rs(0));
              else
                   temp += " -> " + getChildren(rs(0));
              temp += " ] ";
         return temp;
    then call his method by providing any UserID to it and it will return you a string containing complete hierarchy in the following format :
    AAA -> BBB -> CCC -> DDD
    I hope it will help you.
    regards,
    Humayun

  • Can you pass parameters with sub queries

    I have created a Custom folder within a Business Area using a sql query that has multi sub queries. I need to be able to pass date parameters at the top level and at each sub query levels. Is this possible, or how can it be done in Discoverer?
    I have attached an example of the query below.
    select T.title_type_code, T.title_number
    from title_trans T
    where T.title_type_code in ( 'A', 'AC', 'AN','AS','EL', 'ERL','SEL', 'MC', 'MCN', 'MCC', 'MCS', 'ML', 'MLN', 'MLC', 'MLS')
    and T.trans_type_code = 'APPL'
    and trunc(T.effective_date) between to_date('&start_date','DD/MM/YYYY') and to_date('&end_date','DD/MM/YYYY')
    and exists
    (select *
    from title_land_status L     
    where T.title_type_code = L.title_type_code
    and T.title_number = L.title_number
    and L.trans_type_code in ('APPL', 'FLS', 'AVAR')
    --FREEHOLD LAND
    and L.land_status_id in ('15')
    and L.date_completed = (select MAX(L.date_completed)
    from title_land_status L
    where T.title_type_code = L.title_type_code
    and T.title_number = L.title_number
    and trunc(L.date_completed) <= to_date('&end_date','DD/MM/YYYY')
    and L.trans_type_code in ('APPL', 'FLS', 'AVAR')))
    and not exists
    (select *
    from title_land_status L     
    where T.title_type_code = L.title_type_code
    and T.title_number = L.title_number
    and L.trans_type_code in ('APPL', 'FLS', 'AVAR')
    --AB fREEHOLD LAND - NLC, CLC, TLC, ALC
    and L.land_status_id in ('3', '4', '5', '6')
    and L.date_completed = (select MAX(L.date_completed)
    from title_land_status L
    where T.title_type_code = L.title_type_code
    and T.title_number = L.title_number
    and trunc(L.date_completed) <= to_date('&end_date','DD/MM/YYYY')
    and L.trans_type_code in ('APPL', 'FLS', 'AVAR')))
    and not exists
    (select * from title TIT
    where T.title_type_code = TIT.title_type_code
    and T.title_number = TIT.title_number
    and TIT.purpose = 'EMPC')
    order by T.title_type_code;

    Ok,
    I just tried that and it still doesn't pass anything to the prompt.
    I changed the prompt to an edit field and I made the following weblink but when i click the link from an account it doesn't put anything in the prompt and all data for all accounts is shown.
    This is the URL maybe I messed something up...
    https://secure-ausomx###.crmondemand.com/OnDemand/user/Dashboard?OMTHD=ShowDashboard&OMTGT=ReportIFrame&SelDashboardFrm.Dashboard Type=%2fshared%2fCompany_########_Shared_Folder%2f_portal%2f360+Report&Option=rfd&Action=Navigate&P0=1&P1=eq&P2=Account."Account Name"&P3=%%%Name%%%
    thanks

  • List all users with full control on a SharePoint 2013 Sub site from SharePoint Object Model in C#

    If I have a sub site URL and a user with Site Admin, can I list all users in that sub site that have Full Control at that level?
    Any C# code sample?

    Still you can do that, just pass the subsites to your code and from their you can find the users dynamically.
    You could also use SPWeb.Users property to get users assigned to a subsite
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.users(v=office.15).aspx
    alternatively you can also use SPWeb.SiteUsers to get all users
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.siteusers(v=office.15).aspx
    other APIs of help-
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.associatedmembergroup(v=office.15).aspx
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.associatedownergroup(v=office.15).aspx
    http://sharepoint.stackexchange.com/questions/101671/object-model-list-all-users-with-full-control-on-a-sub-site-in-sharepoint-2013
    Hope this helps!
    Ram - SharePoint Architect
    Blog - SharePointDeveloper.in
    Please vote or mark your question answered, if my reply helps you

  • Moved LR to a ew computer Working fine Placed back up in LR folder opened back up folder  All pictues are gray  Numbers of pictures are  shown with correct sub folders However all pictures are gray

    Hello

    I was trying to move pictures to new computer to work with. Did  backup on old computer and copied it to LR file in Pictures.  When I open the file  it lists all folders with correct # of picture  When I click on a folder it  says “Folder can not be found”
    When display grid thumbnails each picture is shown but all gray
    Loaded  new pic from SD and  it appears to be working well
    Yhanks for your help

  • Sub Queries in Hyperion Interactive Reporting

    Hi All,
    I am new to Hyperion.
    How to create Sub Queries in Hyperion IR?????
    Please provide steps to create

    I Assume that you have done creating required OCE, and familiar with the single table query process. You can create sub queries using the Custom SQL feature, which is located under view menu->custom SQL. Please note that the query data model must have at least one table to use this feature.
    Here are the steps to create sub query.
    1. select the main table from table catalog list
    2. select the required columns from table and right click " add selected items" to request section.
    3. go to View menu - > custom SQL
    4. you will see a section which is editable enter all your where clause and sub query section and then process.
    Let me know if you need any detail information.

  • All Joins with Example

    Hi Experts,
    Pls let me know what are all joins available in ABAP??
    One example program for each for better understanding...
    Any useful inputs on this will be highly rewarded.
    Thanks in advance
    Rgds ~ Lakshmiraj

    Hi,
    Joins are used to fetch data fast from Database tables:
    Tables are joined with the proper key fields to fetch the data properly.
    If there are no proper key fields between tables don't use Joins;
    Important thing is that don't USE JOINS FOR CLUSTER tableslike BSEG and KONV.
    Only use for Transparenmt tables.
    You can also use joins for the database VIews to fetch the data.
    JOINS
    ... FROM tabref1 [INNER] JOIN tabref2 ON cond
    Effect
    The data is to be selected from transparent database tables and/or views determined by tabref1 and tabref2. tabref1 and tabref2 each have the same form as in variant 1 or are themselves Join expressions. The keyword INNER does not have to be specified. The database tables or views determined by tabref1 and tabref2 must be recognized by the ABAP Dictionary.
    In a relational data structure, it is quite normal for data that belongs together to be split up across several tables to help the process of standardization (see relational databases). To regroup this information into a database query, you can link tables using the join command. This formulates conditions for the columns in the tables involved. The inner join contains all combinations of lines from the database table determined by tabref1 with lines from the table determined by tabref2, whose values together meet the logical condition (join condition) specified using ON>cond.
    Inner join between table 1 and table 2, where column D in both tables in the join condition is set the same:
    Table 1 Table 2
    A
    B
    C
    D
    D
    E
    F
    G
    H
    a1
    b1
    c1
    1
    1
    e1
    f1
    g1
    h1
    a2
    b2
    c2
    1
    3
    e2
    f2
    g2
    h2
    a3
    b3
    c3
    2
    4
    e3
    f3
    g3
    h3
    a4
    b4
    c4
    3
    |--|||--|
    Inner Join
    A
    B
    C
    D
    D
    E
    F
    G
    H
    a1
    b1
    c1
    1
    1
    e1
    f1
    g1
    h1
    a2
    b2
    c2
    1
    1
    e1
    f1
    g1
    h1
    a4
    b4
    c4
    3
    3
    e2
    f2
    g2
    h2
    |--||||||||--|
    Example
    Output a list of all flights from Frankfurt to New York between September 10th and 20th, 2001 that are not sold out:
    DATA: DATE LIKE SFLIGHT-FLDATE,
    CARRID LIKE SFLIGHT-CARRID,
    CONNID LIKE SFLIGHT-CONNID.
    SELECT FCARRID FCONNID F~FLDATE
    INTO (CARRID, CONNID, DATE)
    FROM SFLIGHT AS F INNER JOIN SPFLI AS P
    ON FCARRID = PCARRID AND
    FCONNID = PCONNID
    WHERE P~CITYFROM = 'FRANKFURT'
    AND P~CITYTO = 'NEW YORK'
    AND F~FLDATE BETWEEN '20010910' AND '20010920'
    AND FSEATSOCC < FSEATSMAX.
    WRITE: / DATE, CARRID, CONNID.
    ENDSELECT.
    If there are columns with the same name in both tables, you must distinguish between them by prefixing the field descriptor with the table name or a table alias.
    Note
    In order to determine the result of a SELECT command where the FROM clause contains a join, the database system first creates a temporary table containing the lines that meet the ON condition. The WHERE condition is then applied to the temporary table. It does not matter in an inner join whether the condition is in the ON or WHEREclause. The following example returns the same solution as the previous one.
    Example
    Output of a list of all flights from Frankfurt to New York between September 10th and 20th, 2001 that are not sold out:
    DATA: DATE LIKE SFLIGHT-FLDATE,
    CARRID LIKE SFLIGHT-CARRID,
    CONNID LIKE SFLIGHT-CONNID.
    SELECT FCARRID FCONNID F~FLDATE
    INTO (CARRID, CONNID, DATE)
    FROM SFLIGHT AS F INNER JOIN SPFLI AS P
    ON FCARRID = PCARRID
    WHERE FCONNID = PCONNID
    AND P~CITYFROM = 'FRANKFURT'
    AND P~CITYTO = 'NEW YORK'
    AND F~FLDATE BETWEEN '20010910' AND '20010920'
    AND FSEATSOCC < FSEATSMAX.
    WRITE: / DATE, CARRID, CONNID.
    ENDSELECT.
    Note
    Since not all of the database systems supported by SAP use the standard syntax for ON conditions, the syntax has been restricted. It only allows those joins that produce the same results on all of the supported database systems:
    Only a table or view may appear to the right of the JOIN operator, not another join expression.
    Only AND is possible in the ON condition as a logical operator.
    Each comparison in the ON condition must contain a field from the right-hand table.
    If an outer join occurs in the FROM clause, all the ON conditions must contain at least one "real" JOIN condition (a condition that contains a field from tabref1 amd a field from tabref2.
    Note
    In some cases, '*' may be specified in the SELECT clause, and an internal table or work area is entered into the INTO clause (instead of a list of fields). If so, the fields are written to the target area from left to right in the order in which the tables appear in the FROM clause, according to the structure of each table work area. There can then be gaps between table work areas if you use an Alignment Request. For this reason, you should define the target work area with reference to the types of the database tables, not simply by counting the total number of fields. For an example, see below:
    Variant 3
    ... FROM tabref1 LEFT [OUTER] JOIN tabref2 ON cond
    Effect
    Selects the data from the transparent database tables and/or views specified in tabref1 and tabref2. tabref1 und tabref2 both have either the same form as in variant 1 or are themselves join expressions. The keyword OUTER can be omitted. The database tables or views specified in tabref1 and tabref2 must be recognized by the ABAP-Dictionary.
    In order to determine the result of a SELECT command where the FROM clause contains a left outer join, the database system creates a temporary table containing the lines that meet the ON condition. The remaining fields from the left-hand table (tabref1) are then added to this table, and their corresponding fields from the right-hand table are filled with ZERO values. The system then applies the WHERE condition to the table.
    Left outer join between table 1 and table 2 where column D in both tables set the join condition:
    Table 1 Table 2
    A
    B
    C
    D
    D
    E
    F
    G
    H
    a1
    b1
    c1
    1
    1
    e1
    f1
    g1
    h1
    a2
    b2
    c2
    1
    3
    e2
    f2
    g2
    h2
    a3
    b3
    c3
    2
    4
    e3
    f3
    g3
    h3
    a4
    b4
    c4
    3
    |--|||--|
    Left Outer Join
    A
    B
    C
    D
    D
    E
    F
    G
    H
    a1
    b1
    c1
    1
    1
    e1
    f1
    g1
    h1
    a2
    b2
    c2
    1
    1
    e1
    f1
    g1
    h1
    a3
    b3
    c3
    2
    NULL
    NULL
    NULL
    NULL
    NULL
    a4
    b4
    c4
    3
    3
    e2
    f2
    g2
    h2
    |--||||||||--|
    Example
    Output a list of all custimers with their bookings for October 15th, 2001:
    DATA: CUSTOMER TYPE SCUSTOM,
    BOOKING TYPE SBOOK.
    SELECT SCUSTOMNAME SCUSTOMPOSTCODE SCUSTOM~CITY
    SBOOKFLDATE SBOOKCARRID SBOOKCONNID SBOOKBOOKID
    INTO (CUSTOMER-NAME, CUSTOMER-POSTCODE, CUSTOMER-CITY,
    BOOKING-FLDATE, BOOKING-CARRID, BOOKING-CONNID,
    BOOKING-BOOKID)
    FROM SCUSTOM LEFT OUTER JOIN SBOOK
    ON SCUSTOMID = SBOOKCUSTOMID AND
    SBOOK~FLDATE = '20011015'
    ORDER BY SCUSTOMNAME SBOOKFLDATE.
    WRITE: / CUSTOMER-NAME, CUSTOMER-POSTCODE, CUSTOMER-CITY,
    BOOKING-FLDATE, BOOKING-CARRID, BOOKING-CONNID,
    BOOKING-BOOKID.
    ENDSELECT.
    If there are columns with the same name in both tables, you must distinguish between them by prefixing the field descriptor with the table name or using an alias.
    Note
    For the resulting set of a SELECT command with a left outer join in the FROM clause, it is generally of crucial importance whether a logical condition is in the ON or WHERE condition. Since not all of the database systems supported by SAP themselves support the standard syntax and semantics of the left outer join, the syntax has been restricted to those cases that return the same solution in all database systems:
    Only a table or view may come after the JOIN operator, not another join statement.
    The only logical operator allowed in the ON condition is AND.
    Each comparison in the ON condition must contain a field from the right-hand table.
    Comparisons in the WHERE condition must not contain a field from the right-hand table.
    The ON condition must contain at least one "real" JOIN condition (a condition in which a field from tabref1 as well as from tabref2 occurs).
    Note
    In some cases, '*' may be specivied as the field list in the SELECT clause, and an internal table or work area is entered in the INTO clause (instead of a list of fields). If so, the fields are written to the target area from left to right in the order in which the tables appear in the llen in der FROM clause, according to the structure of each table work area. There can be gaps between the table work areas if you use an Alignment Request. For this reason, you should define the target work area with reference to the types of the database tables, as in the following example (not simply by counting the total number of fields).
    Example
    Example of a JOIN with more than two tables: Select all flights from Frankfurt to New York between September 10th and 20th, 2001 where there are available places, and display the name of the airline.
    DATA: BEGIN OF WA,
    FLIGHT TYPE SFLIGHT,
    PFLI TYPE SPFLI,
    CARR TYPE SCARR,
    END OF WA.
    SELECT * INTO WA
    FROM ( SFLIGHT AS F INNER JOIN SPFLI AS P
    ON FCARRID = PCARRID AND
    FCONNID = PCONNID )
    INNER JOIN SCARR AS C
    ON FCARRID = CCARRID
    WHERE P~CITYFROM = 'FRANKFURT'
    AND P~CITYTO = 'NEW YORK'
    AND F~FLDATE BETWEEN '20010910' AND '20010920'
    AND FSEATSOCC < FSEATSMAX.
    WRITE: / WA-CARR-CARRNAME, WA-FLIGHT-FLDATE, WA-FLIGHT-CARRID,
    WA-FLIGHT-CONNID.
    ENDSELECT.
    Syntax
    ... [(] {dbtab_left [AS tabalias_left]} | join
    {[INNER] JOIN}|{LEFT [OUTER] JOIN}
    {dbtab_right [AS tabalias_right] ON join_cond} [)] ... .
    Effect
    The join syntax represents a recursively nestable join expression. A join expression consists of a left-hand and a right- hand side, which are joined either by means of [INNER] JOIN or LEFT [OUTER] JOIN . Depending on the type of join, a join expression can be either an inner ( INNER) or an outer (LEFT OUTER) join. Every join expression can be enclosed in round brackets. If a join expression is used, the SELECT command circumvents SAP buffering.
    On the left-hand side, either a single database table, a view dbtab_left, or a join expression join can be specified. On the right-hand side, a single database table or a view dbtab_right as well as join conditions join_cond can be specified after ON. In this way, a maximum of 24 join expressions that join 25 database tables or views with each other can be specified after FROM.
    AS can be used to specify an alternative table name tabalias for each of the specified database table names or for every view. A database table or a view can occur multiple times within a join expression and, in this case, have various alternative names.
    The syntax of the join conditions join_cond is the same as that of the sql_cond conditions after the addition WHERE, with the following differences:
    At least one comparison must be specified after ON.
    Individual comparisons may be joined using AND only.
    All comparisons must contain a column in the database table or the view dbtab_right on the right-hand side as an operand.
    The following language elements may not be used: BETWEEN, LIKE, IN.
    No sub-queries may be used.
    For outer joins, only equality comparisons (=, EQ) are possible.
    If an outer join occurs after FROM, the join condition of every join expression must contain at least one comparison between columns on the left-hand and the right-hand side.
    In outer joins, all comparisons that contain columns as operands in the database table or the view dbtab_right on the right-hand side must be specified in the corresponding join condition. In the WHERE condition of the same SELECT command, these columns are not allowed as operands.
    Resulting set for inner join
    The inner join joins the columns of every selected line on the left- hand side with the columns of all lines on the right-hand side that jointly fulfil the join_cond condition. A line in the resulting set is created for every such line on the right-hand side. The content of the column on the left-hand side may be duplicated in this case. If none of the lines on the right-hand side fulfils the join_cond condition, no line is created in the resulting set.
    Resulting set for outer join
    The outer join basically creates the same resulting set as the inner join, with the difference that at least one line is created in the resulting set for every selected line on the left-hand side, even if no line on the right-hand side fulfils the join_cond condition. The columns on the right-hand side that do not fulfil the join_cond condition are filled with null values.
    Example
    Join the columns carrname, connid, fldate of the database tables scarr, spfli and sflight by means of two inner joins. A list is created of the flights from p_cityfr to p_cityto. Alternative names are used for every table.
    PARAMETERS: p_cityfr TYPE spfli-cityfrom,
    p_cityto TYPE spfli-cityto.
    DATA: BEGIN OF wa,
    fldate TYPE sflight-fldate,
    carrname TYPE scarr-carrname,
    connid TYPE spfli-connid,
    END OF wa.
    DATA itab LIKE SORTED TABLE OF wa
    WITH UNIQUE KEY fldate carrname connid.
    SELECT ccarrname pconnid f~fldate
    INTO CORRESPONDING FIELDS OF TABLE itab
    FROM ( ( scarr AS c
    INNER JOIN spfli AS p ON pcarrid = ccarrid
    AND p~cityfrom = p_cityfr
    AND p~cityto = p_cityto )
    INNER JOIN sflight AS f ON fcarrid = pcarrid
    AND fconnid = pconnid ).
    LOOP AT itab INTO wa.
    WRITE: / wa-fldate, wa-carrname, wa-connid.
    ENDLOOP.
    Example
    Join the columns carrid, carrname and connid of the database tables scarr and spfli using an outer join. The column connid is set to the null value for all flights that do not fly from p_cityfr. This null value is then converted to the appropriate initial value when it is transferred to the assigned data object. The LOOP returns all airlines that do not fly from p_cityfr.
    PARAMETERS p_cityfr TYPE spfli-cityfrom.
    DATA: BEGIN OF wa,
    carrid TYPE scarr-carrid,
    carrname TYPE scarr-carrname,
    connid TYPE spfli-connid,
    END OF wa,
    itab LIKE SORTED TABLE OF wa
    WITH NON-UNIQUE KEY carrid.
    SELECT scarrid scarrname p~connid
    INTO CORRESPONDING FIELDS OF TABLE itab
    FROM scarr AS s
    LEFT OUTER JOIN spfli AS p ON scarrid = pcarrid
    AND p~cityfrom = p_cityfr.
    LOOP AT itab INTO wa.
    IF wa-connid = '0000'.
    WRITE: / wa-carrid, wa-carrname.
    ENDIF.
    ENDLOOP.
    Cheers,
    vasavi.
    kindly reward if helpful.

  • Sub queries in CR 11

    Post Author: pranathi20
    CA Forum: Data Connectivity and SQL
    Hi All,
    Can someone help me with the below SQL query? I am not sure how to have the sub query in CR
    SELECT   x.created_on, x.ssn, x.age  ,        max(DECODE(x.rn,1,x.nlsi_answer)) BIO001  ,        max(DECODE(x.rn,4,x.nlsi_answer)) BIO116  ,    x.nlsipvsc
      FROM    (SELECT nlsiview.created_on created_on           ,      nlsiview.ssn     ssn           ,      nlsiview.age     age           ,      nlsiview.answer  nlsi_answer           ,      ROW_NUMBER() OVER (PARTITION BY nlsiview.created_on, nlsiview.ssn                                     ORDER BY     NULL) rn           FROM   nlsiview           ) x  GROUP BY x.created_on, x.ssn, x.age    ORDER BY x.created_on, x.ssn  /

    I Assume that you have done creating required OCE, and familiar with the single table query process. You can create sub queries using the Custom SQL feature, which is located under view menu->custom SQL. Please note that the query data model must have at least one table to use this feature.
    Here are the steps to create sub query.
    1. select the main table from table catalog list
    2. select the required columns from table and right click " add selected items" to request section.
    3. go to View menu - > custom SQL
    4. you will see a section which is editable enter all your where clause and sub query section and then process.
    Let me know if you need any detail information.

  • Sub queries

    i have a longish query which runs correctly in Oracle 8i Lite thro SQL Plus but does not run when using JDBC.
    The query has multiple subqueries and it looks like
    delete from node_initial_values d where d.node_id in (select c.node_id from node_master c where c.node_id=d.node_id and c.node_id in (select e.node_id from network_design e where c.node_id=e.node_id and e.network_id in (select b.network_id from network_master b where e.network_id=b.network_id and b.network_id in (select g.network_id from output_network_scenario g where g.network_id=b.network_id and g.output_network_master_id in (select a.output_network_master_id from output_network_master a where a.output_name= 'network three')))));
    assume all the tables exist with correct data. the above query works perfectly well in SQL*plus but when i use
    the following code i get an error
    PreparedStatement deleteNodeInitialValuesPst=getConn.prepareStatement("delete from node_initial_values d where .... a where a.output_name= ?)))))");
    deleteNodeInitialValuesPst.setString(1,"network three");
    deleteNodeInitialValuesPst.executeUpdate();
    getConn.commit();
    ... rest of the code
    the error code oracle 8i lite gives is
    java.sql.SQLException: [POL-4200] bad action for transaction operation
    would really appreciate any help in this regard...
    specifically can anyone tell me if prepared statement is the correct function to use here...
    thanks

    I made the following changes:
    changes to the code, new code mentioned below
    changed the database to oracle 8i enterprise edition running on NT.
    new code now is
    // connetion parameter and other code here
    String deleteNodeInitialValuesStr=
    "delete from node_initial_values d where d.node_id in (select c.node_id from node_master c where c.node_id=d.node_id and c.node_id in (select e.node_id from network_design e where c.node_id=e.node_id and e.network_id in (select b.network_id from network_master b where e.network_id=b.network_id and b.network_id in (select g.network_id from output_network_scenario g where g.network_id=b.network_id and g.output_network_master_id in (select a.output_network_master_id from output_network_master a where a.output_name='"+nextElementStr+"')))))";
    Statement deleteNodeInitialValuesSt=getConn.createStatement();
              deleteNodeInitialValuesSt.executeQuery(deleteNodeInitialValuesStr);
    getConn.commit();
    } // end try
    catch(SQLException ex) {
         while(ex !=null){
    out.println("Java SQL Exception: " + ex.getMessage()+"<br>");
    out.println("Vendor error code: " + ex.getErrorCode()+ "<br>");
    out.println("SQL State: " + ex.getSQLState() + "<br>");
    ex=ex.getNextException();
    } // end while
    } // end catch
    // more code here
    the output i get is
    Java SQL Exception: 202
    Vendor error code: 0
    SQL State: null
    I turned off getConn.commit(), but the error code remains the same. is there an alternative to the sub queries above. where can i get the meaning of the error codes thrown by the exception ?
    thanks

Maybe you are looking for