How to build query to get tree architecture of self referencing table

Dear all,
I have the following table design :
This is a self referencing table representing a set of SubCategories which can have parent sub categories or not. I did not show here the Category table.
If the Subcategory has the ParentSubCategory ID = null, then this is a root subcategory otherwise it is a child of a parent sub category.
What I am looking for is the easy way to display the structure level by ProductCategoryID ?
Thanks for helps

you can use a recursive logic based on CTE for that
something like this would be enough
;WITH ProdSubCat_Hiererchy
AS
SELECT psc.ProductSubCategoryID,c.CategoryName,psc.ParentSubCategoryID, psc.Name,CAST(psc.Name AS varchar(max)) AS [Path],1 AS [level]
FROM ProductSubCategory psc
INNER JOIN Category c
ON c.CategoryID = psc.ProductCategoryID
WHERE psc.ParentSubCategoryID IS NULL
UNION ALL
SELECT psc.ProductSubCategoryID,c.CategoryName,psc.ParentSubCategoryID, psc.Name,CAST(psch.[Path] + '/' + psc.Name AS varchar(max)) AS [Path],psch.[level] + 1
FROM ProductSubCategory psc
INNER JOIN Category c
ON c.CategoryID = psc.ProductCategoryID
INNER JOIN ProdSubCat_Hiererchy psch
ON psch.ProductSubCategoryID = psc.ParentSubCategoryID
SELECT *
FROM ProdSubCat_Hiererchy
ORDER BY LEFT([Path],CHARINDEX('/',[Path]+'/')-1),[Level]
OPTION (MAXRECURSION 0)
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • SQL query to get last 10 records in the table?

    Hi,
    Can anyone tell me the SQL query to get last 10 records in the table?
    Thanks!!
    MCP

    Please, define what "last" means. Sets are unordered by definition, so if you want to retrieve rows from a table in a specific order you need to specify what that order is - e.g. by maintaining a value in a column (or a combination of columns) that you can use in the ORDER BY clause of the SELECT statement.
    If, for instance, you kept the time when the row was inserted in a special column (InsertedTime), you could use this in your query like this:
    select top (10)
      <column list>
      from <table or view>
      where <restriction(s)>
      order by InsertedTime desc;
    ML
    Matija Lah, SQL Server MVP
    http://milambda.blogspot.com

  • JPA: How to initialise an entity for a self-referencing table?

    I am working on a project that requires a self-referencing table:
    mysql> show create table attributes\G
    *************************** 1. row ***************************
           Table: attributes
    Create Table: CREATE TABLE `attributes` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `parent` int(11) DEFAULT NULL,
      `type` int(11) DEFAULT NULL,
      `name` varchar(128) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `parent` (`parent`),
      KEY `type` (`type`),
      CONSTRAINT `attributes_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `attributes` (`id`),
      CONSTRAINT `attributes_ibfk_2` FOREIGN KEY (`type`) REFERENCES `attributes` (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
    I used NetBeans to generate an entity class from the table:
    @Entity
    @Table(name = "attributes")
    @XmlRootElement
    @NamedQueries({
        @NamedQuery(name = "Attributes.findAll", query = "SELECT a FROM Attributes a"),
        @NamedQuery(name = "Attributes.findById", query = "SELECT a FROM Attributes a WHERE a.id = :id"),
        @NamedQuery(name = "Attributes.findByName", query = "SELECT a FROM Attributes a WHERE a.name = :name")})
    public class Attributes implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @Column(name = "id")
        private Integer id;
        @Size(max = 128)
        @Column(name = "name")
        private String name;
        @OneToMany(mappedBy = "parent")
        private Collection<Attributes> attributesCollection;
        @JoinColumn(name = "parent", referencedColumnName = "id")
        @ManyToOne
        private Attributes parent;
        @OneToMany(mappedBy = "type")
        private Collection<Attributes> attributesCollection1;
        @JoinColumn(name = "type", referencedColumnName = "id")
        @ManyToOne
        private Attributes type;
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "attributes")
        private Collection<ItemAttributes> itemAttributesCollection;
        @OneToMany(mappedBy = "ivalue")
        private Collection<ItemAttributes> itemAttributesCollection1;
    But how can I write a constructor for this entity? The auto-generated code gets around the issue by doing nothing; the constructor is empty. I can't help thinking that if I set the parent and type references to anything with new Attributes(), then it will recurse out of control. What else can/shall I do? I know how to rewrite it to not use the entity relations, but I'd prefer to make it work.

    Cymae wrote:
    I don't want to call the hash table creation method because from what i understand about interfaces the idea is that your main method doesnt know the table is actually a hash table...is that right?That's not exactly the idea. The idea to use the interface as the type instead of the implementation, is that your class probably doesn't need to know the full type. This makes it easy to change the implementation of the interface if needed. However, somebody at some point has to create the concrete object, a HashTable.
    Basically, an interface describes a behavior, and a class that implements an interface decides how to actually perform this behavior. It is obviously impossible to perform the behavior if you are not told how to perform it.
    Table table = new HashTable() is the correct way to do it. This means that if you ever need you Table implementation to change, the only thing you need to change in your whole class is this line. For example you might want Table table = new FileTable().

  • Query output help: Display self-referencing table

    Hello,
    I'm trying to display in a cfoutput a self-referencing table.
    I'll start by showing some of the data in the table.
    There are only 3 columns, pl_id (auto increment id pri-key),
    pl_name and pl_parent_id (it's 0 if it's a parent, otherwise it's
    the pl_id value for the parent).
    pl_id pl_name pl_parent_id
    1 Country 0
    2 Food 0
    3 US 1
    4 Japan 1
    5 Hamburger 2
    6 Idaho 3
    7 Florida 3
    8 Cheese 2
    What I'm trying to output is something like this:
    Country - US - Idaho (3 levels here) or
    Country - US - Florida (or if there are only 2 levels like
    the next line)
    Food - Cheese
    I've tried using a cfoutput with a cfloop as well as grouping
    but not having any luck. Could someone clear my clouded head on
    this one?
    thanks much,
    Joe
    ps. Adobe should really use a fixed width font for these
    forums, it's impossible to line up table info!

    JoeNH2k wrote:
    > It would be nice if it were that easy, I (of course)
    tried that. The sort order
    > of the query doesn't matter. The data is not sorted once
    the function runs. The
    > sort has to come after the select box is populated by
    the function. I need to
    > get the data at this point and sort it, probably somehow
    creating a structure
    > or array from this data and sorting that(?).
    >
    <cfset myArr = ArrayNew(1)>
    <cfloop query="qryGetAll">
    <cfset temp = ArrayAppend(myArr,
    "#getNameWithParent(pl_id)#")>
    </cfloop>
    <cfset ArraySort(myArr, "textnocase", "asc")>
    <cfset myList = ArrayToList(myArr, ",")>
    then loop through myList to populate your <select>...
    how about that?
    Azadi Saryev
    Sabai-dee.com
    Vientiane, Laos
    http://www.sabai-dee.com

  • How to check query is getting reused after changing parametr cursor_sharing

    Hello,
    Oracle Version: 11g
    OS Version: Windows 2003 64Bit
    How to find if a particular query is getting reused after change in a cursor_sharing parameter from EXACT to SIMILAR.
    Which set of Views/DD's should i query go get the relevant details.
    Thanks in advance.
    -Vijay.

    SQL> desc v$sqlarea
    Name                                                  Null?    Type
    SQL_TEXT                                                       VARCHAR2(1000)
    SQL_FULLTEXT                                                   CLOB
    SQL_ID                                                         VARCHAR2(13)
    SHARABLE_MEM                                                   NUMBER
    PERSISTENT_MEM                                                 NUMBER
    RUNTIME_MEM                                                    NUMBER
    SORTS                                                          NUMBER
    VERSION_COUNT                                                  NUMBER
    LOADED_VERSIONS                                                NUMBER
    OPEN_VERSIONS                                                  NUMBER
    USERS_OPENING                                                  NUMBER
    FETCHES                                                        NUMBER
    EXECUTIONS                                                     NUMBER
    PX_SERVERS_EXECUTIONS                                          NUMBER
    END_OF_FETCH_COUNT                                             NUMBER
    USERS_EXECUTING                                                NUMBER
    LOADS                                                          NUMBER
    FIRST_LOAD_TIME                                                VARCHAR2(19)
    INVALIDATIONS                                                  NUMBER
    PARSE_CALLS                                                    NUMBER
    DISK_READS                                                     NUMBER
    DIRECT_WRITES                                                  NUMBER
    BUFFER_GETS                                                    NUMBER
    APPLICATION_WAIT_TIME                                          NUMBER
    CONCURRENCY_WAIT_TIME                                          NUMBER
    CLUSTER_WAIT_TIME                                              NUMBER
    USER_IO_WAIT_TIME                                              NUMBER
    PLSQL_EXEC_TIME                                                NUMBER
    JAVA_EXEC_TIME                                                 NUMBER
    ROWS_PROCESSED                                                 NUMBER
    COMMAND_TYPE                                                   NUMBER
    OPTIMIZER_MODE                                                 VARCHAR2(10)
    OPTIMIZER_COST                                                 NUMBER
    OPTIMIZER_ENV                                                  RAW(797)
    OPTIMIZER_ENV_HASH_VALUE                                       NUMBER
    PARSING_USER_ID                                                NUMBER
    PARSING_SCHEMA_ID                                              NUMBER
    PARSING_SCHEMA_NAME                                            VARCHAR2(30)
    KEPT_VERSIONS                                                  NUMBER
    ADDRESS                                                        RAW(4)
    HASH_VALUE                                                     NUMBER
    OLD_HASH_VALUE                                                 NUMBER
    PLAN_HASH_VALUE                                                NUMBER
    MODULE                                                         VARCHAR2(64)
    MODULE_HASH                                                    NUMBER
    ACTION                                                         VARCHAR2(64)
    ACTION_HASH                                                    NUMBER
    SERIALIZABLE_ABORTS                                            NUMBER
    OUTLINE_CATEGORY                                               VARCHAR2(64)
    CPU_TIME                                                       NUMBER
    ELAPSED_TIME                                                   NUMBER
    OUTLINE_SID                                                    VARCHAR2(40)
    LAST_ACTIVE_CHILD_ADDRESS                                      RAW(4)
    REMOTE                                                         VARCHAR2(1)
    OBJECT_STATUS                                                  VARCHAR2(19)
    LITERAL_HASH_VALUE                                             NUMBER
    LAST_LOAD_TIME                                                 DATE
    IS_OBSOLETE                                                    VARCHAR2(1)
    CHILD_LATCH                                                    NUMBER
    SQL_PROFILE                                                    VARCHAR2(64)
    PROGRAM_ID                                                     NUMBER
    PROGRAM_LINE#                                                  NUMBER
    EXACT_MATCHING_SIGNATURE                                       NUMBER
    FORCE_MATCHING_SIGNATURE                                       NUMBER
    LAST_ACTIVE_TIME                                               DATE
    BIND_DATA                                                      RAW(2000)

  • How to build Hierarchy and get values from DAX Evaluation Query?

    i have create Calander Hierachy for Year,Quarter,Month... in this invisible tabuler model medata properties.
    any one give steps for create Hierachy and Get Data From DAX evaluation context ?.
    VenkadesanPerumal

    Venkadesan, is this still an issue?
    Thanks!
    Ed Price, Azure & Power BI Customer Program Manager (Blog,
    Small Basic,
    Wiki Ninjas,
    Wiki)
    Answer an interesting question?
    Create a wiki article about it!

  • How to build query which list only active PC's

    Hi guys,
    I have to install SCCM client on many devices in my enviroment. Unfortunately, SCCM has found amny devices which still have accounts in AD but are not used for looong time. I would like to list only devices, which hasen't installed SCCM client yet but are
    active in my enviroment. 
    That is possible? If yes, that will be glad to hear how build this query.
    Thank you.

    If you don't want those not used devices, why don't you stop discovering them. In the
    Active Directory System Discovery there is a tab Options
    in which you can configure to not discover computers account that have not been used.
    My Blog: http://www.petervanderwoude.nl/
    Follow me on twitter: pvanderwoude

  • How to build query to give daily balance across bank accounts? (to then plot in a graph)

    How would one build a query to give daily balance across bank accounts? (to then plot in a graph)
    Assumptions:
    * There is a table TRANSACTIONS which includes columns TRANS_DATE, AMOUNT and BANK_ID. It does NOT include a column for balance. So current balance for a bank account is the sum of the AMOUNTs for that BANK_ID for example. Balance on date XX will be the sum
    of all AMOUNTS for that BANK_ID for all TRANS_DATE's prior and including the date XX.
    * There is not necessarily transactions on every day for each bank
    * Table BANKS which has BANK_ID and TITLE
    Would like a query that gives: Supply StartDate and EndDate for the query:
    Date Bank1Balance Bank2Balance Bank3Balance TotalBalance
    1/1/15 $100 $200 $100 $400
    1/2/15 $200 $200 $100 $500
    etc

    You'll find examples of queries for computing balances in various contexts in Balances.zip in my public databases folder at:
    https://onedrive.live.com/?cid=44CC60D7FEA42912&id=44CC60D7FEA42912!169
    If you have difficulty opening the link copy its text (NB, not the link location) and paste it into your browser's address bar.
    The queries in this little demo file return balances per transaction, however, whereas you appear to wish to return balances at close of business per day.  This can easily be done by means of a subquery which sums all transactions to date.  To return
    balances for all dates regardless of whether or not any transactions have been undertaken on the day, an auxiliary calendar table can be introduced into the database to plug the gaps,  The Calendar.zip file in my same OneDrive folder has means of generating
    such a table.
    With the introduction of an auxiliary calendar table into the database a query can then be written to return the balance per customer at close of business per day over the period 2009 - 2012 covered by the data in the Transactions table:
    SELECT CustomerID, Firstname, LastName, calDate,
       (SELECT SUM(TransactionAmount)
         FROM Transactions
         WHERE Transactions.CustomerID = Customers.CustomerID
         AND Transactions.TransactionDate <= Calendar.calDate) AS Balance
    FROM Calendar,Customers
    WHERE calDate BETWEEN #2009-01-01# AND #2012-12-31#
    ORDER BY CustomerID, CalDate;
    Rows for each customer/date are returned by means of the Cartesian product of the Calendar and Customers tables (the latter analogous to your Banks table), and the subquery returns the balance at close of each day by correlating the Transactions table with
    the Customers and Calendar tables, returning the sum of all transactions per customer up to and including the date in question.  In this example credit and debit transactions are expressed as positive and negative values in a single column of course,
    but where separate credit and debit columns are used its merely a case of summing (Credit-Debit), as done in some of the examples in my demo.
    To return the data in a horizontal format per date I'd suggest the use of a report which returns one row per date, and within it a multi-column subreport in across-then down column layout, linking the subreport to the parent report on the date columns.
    Ken Sheridan, Stafford, England

  • How to build "Query by example" Report?

    I want to create a report which allows user to select which columns to return.
    It is similar to "Query by example" form. Have someone done that before and share me the PL/SQL how to do that?
    Thanks in advance.

    I got the answer, u need to set table.setFilterModel("") and refresh panel collection which contains this table
    whenever u need to make "Query By Example" button of panel collection invisible.

  • How to comple query to get correct results?

    Hello,
    I am having problems getting the results from a query.  I have 2 tables:
    Marriage table
    People1ID People2ID DateMarried
    1 4 5/5/2014
    5 7 6/5/2014
    2 3 7/5/2014
    People table
    PeopleID First Last
    1 Bob Jones
    2 Mary Smith
    3 Steve Smith
    4 Jane Jones
    5 Robert Apple
    6 Julie Jackson
    7 Diane Apple
    Looking for result like this:
    First1 Last1 First2 Last2 DateMarried
    Bob Jones Jane Jones 5/5/2014
    Robert Apple Diane Apple 6/5/2014
    Mary Smith Steve Smith 6/5/2014
    Paul

    I'm little confuse on your expected result specially on the third row column "Datemarried". Are you sure that its 6/5/2014. I think its 7/5/2014. Anyway you can try this query.
    select b.[First], b.[Last],
    c.[First],c.[Last], 
    a.DateMarried from marriage a
    left outer join People b
    on a.people1id=b.peopleid
    left outer join People c
    on a.people2id=c.peopleid
    this will be the result:
    First Last
    First Last
    DateMarried
    Bob Jones
    Jane Jones
    5/5/2014
    Robert Apple
    Diane Apple
    6/5/2014
    Mary Smith
    Steve Smith
    7/5/2014

  • How to build a lock escalation tree?

    Hello!
    Concurrent users lock many rows in different tables. Sometimes
    one session waits to lock row, which is locked by another
    session.
    Locks are made by SQL statements.
    I would like to present tree of SQL statements which lock (first
    level) and as children SQL - statements waiting for release lock
    by their parents.
    It would be very helpul in finding dependencies and app places,
    where deadlock can occur.
    Do you know system SQL statement or tool, which could produce
    result I need?
    TIA,
    Witek

    I modified the script I posted earlier to include the waiters SQL
    statement. You'll have to verify that this is what you're looking
    for and that it's correct. I did some simple testing and it
    seemed to work.
    set term off;
    set null ~;
    set arraysize 10
    drop table lock_holders;
    drop table dba_locks_temp;
    create table dba_locks_temp as select * from dba_locks;
    create table lock_holders as
    select w.session_id waiting_session,
    h.session_id holding_session,
    w.lock_type,
    h.mode_held,
    w.mode_requested,
    w.lock_id1,
    w.lock_id2,
    a.sql_text sql_stmnt
    from dba_locks_temp w, dba_locks_temp h, v$session s, v$sqltext
    a
    where h.blocking_others = 'Blocking'
    and h.mode_held != 'None'
    and h.mode_held != 'Null'
    and w.mode_requested != 'None'
    and w.lock_type = h.lock_type
    and w.lock_id1 = h.lock_id1
    and w.lock_id2 = h.lock_id2
    and w.session_id=s.sid(+)
    and s.sql_address = a.address
    and s.status = 'ACTIVE'
    and s.type !='BACKGROUND'
    order by a.address
    ,a.piece;
    commit;
    drop table dba_locks_temp;
    insert into lock_holders
    select holding_session, null, 'None', null, null, null, null,
    null
    from lock_holders
    minus
    select waiting_session, null, 'None', null, null, null, null,
    null
    from lock_holders;
    commit;
    /* set charwidth 17; */
    set wrap off;
    set term on;
    select substr(lpad(' ',3*(level-1)) ||
    substr(waiting_session,1,10),1,20)
    waiting_session, sql_stmnt
    from lock_holders
    connect by prior waiting_session = holding_session
    start with holding_session is null;
    set term off;
    drop table lock_holders;
    set wrap on;
    set term on;
    Here's the output it generated from a test I ran:
    WAITING_SESSION SQL_STMNT
    9 ~
    11 update emp set acct_segment1='1111111',
    acct_segment2='2222222',
    11 acct_segment3='3333333',
    acct_segment4='4444444', acct_segment5
    11 ='5555555', acct_segment6='6666666' where
    employee='AGLICK'
    If you wanted you could also add username and osuser from
    v$session to get the users Oracle userid and their network id.

  • How to write query to get the following o/p

    Hi i've the following data and
    create table hirarchical(prnt_id number,child_id number)
    insert into hirarchical values(1,2)
    insert into hirarchical values(1,3)
    insert into hirarchical values(1,4)
    insert into hirarchical values(2,5)
    insert into hirarchical values(2,6)
    insert into hirarchical values(2,7)
    insert into hirarchical values(3,8)and
    If i give in where condition prnt_id=1 then
    the o/p should be 7 instead of 1 as it's having all connected childs...
    thanks in advance

    user10502250 wrote:
    If my reply is correct or helpful please mark it so.Begging for points is unprofessional and considered poor netiquette. It also makes a mockery of the already poor points system, by putting pressure on the original poster to award points for answers that may or may not be the most helpful or correct. If your answer is correct or helpful and meets the needs of the original poster then it is entirely up to them to award points as they see fit when they feel they have had sufficient answers or responses. Most of the people on the forum who have gained a lot of points have done so through providing good answers and without needing to ask for them. Please avoid such begging in future.

  • Oracle SQL query for getting specific special characters from a table

    Hi all,
    This is my table
    Table Name- Table1
    S.no    Name
    1          aaaaaaaa
    2          a1234sgjghb
    3          a@3$%jkhkjn
    4          abcd-dfghjik
    5          bbvxzckvbzxcv&^%#
    6          ashgweqfg/gfjwgefj////
    7          sdsaf$([]:'
    8          <-fdsjgbdfsg
    9           dfgfdgfd"uodf
    10         aaaa  bbbbz#$
    11         cccc dddd-/mnm
    The output has to be
    S.no    Name
    3          a@3$%jkhkjn
    5          bbvxzckvbzxcv&^%#
    7          sdsaf$([]:'
    8          <-fdsjgbdfsg
    10         aaaa  bbbbz#$
    It has to return "Name" column which is having special characters,whereas some special chars like -, / ," and space are acceptable.
    The Oracle query has to print columns having special characters excluding -,/," and space
    Can anyone help me to get a SQL query for the above.
    Thanks in advance.

    You can achieve it in multiple ways. Here are few.
    SQL> with t
      2  as
      3  (
      4  select 1 id, 'aaaaaaaa' name from dual union all
      5  select 2 id, 'a1234sgjghb' name from dual union all
      6  select 3 id, 'a@3$%jkhkjn' name from dual union all
      7  select 4 id, 'abcd-dfghjik' name from dual union all
      8  select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
      9  select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
    10  select 7 id, 'sdsaf$([]:''' name from dual union all
    11  select 8 id, '<-fdsjgbdfsg' name from dual union all
    12  select 9 id, 'dfgfdgfd"uodf' name from dual union all
    13  select 10 id, 'aaaa  bbbbz#$' name from dual union all
    14  select 11 id, 'cccc dddd-/mnm' name from dual
    15  )
    16  select *
    17    from t
    18   where regexp_like(translate(name,'a-/" ','a'), '[^[:alnum:]]');
            ID NAME
             3 a@3$%jkhkjn
             5 bbvxzckvbzxcv&^%#
             7 sdsaf$([]:'
             8 <-fdsjgbdfsg
            10 aaaa  bbbbz#$
    SQL> with t
      2  as
      3  (
      4  select 1 id, 'aaaaaaaa' name from dual union all
      5  select 2 id, 'a1234sgjghb' name from dual union all
      6  select 3 id, 'a@3$%jkhkjn' name from dual union all
      7  select 4 id, 'abcd-dfghjik' name from dual union all
      8  select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
      9  select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
    10  select 7 id, 'sdsaf$([]:''' name from dual union all
    11  select 8 id, '<-fdsjgbdfsg' name from dual union all
    12  select 9 id, 'dfgfdgfd"uodf' name from dual union all
    13  select 10 id, 'aaaa  bbbbz#$' name from dual union all
    14  select 11 id, 'cccc dddd-/mnm' name from dual
    15  )
    16  select *
    17    from t
    18   where translate
    19         (
    20            lower(translate(name,'a-/" ','a'))
    21          , '.0123456789abcdefghijklmnopqrstuvwxyz'
    22          , '.'
    23         ) is not null;
            ID NAME
             3 a@3$%jkhkjn
             5 bbvxzckvbzxcv&^%#
             7 sdsaf$([]:'
             8 <-fdsjgbdfsg
            10 aaaa  bbbbz#$
    SQL>

  • How to execute query to store the result in the target table column ?

    Hi
    Source: Oracle
    Target: Oracle
    ODI: 11g
    I have an interface which loads the data from source table to target. Some of the columns in the target tables are automatically mapped with source table. Some of the column remain un-mapped. Those who remain un-mapped, I want to load the values in that column by executing an query. So can anybody tell me where I should mention that query whose result would become the value of the specific column.
    -Thanks,
    Shrinivas

    Actually I select the column from the target table then in the Property Inspector-->Mapping properties-->Implementation
    tab I have written the query which retrieve the value for that column. Is the right place to write the query? How can do this ?
    -Shrinivas

  • Query to get rows betwen x and y + table total row count

    Hi,
    I try get rows between e.g. 100 and 150 when I sort by some column
    My query is now like this
    SELECT  *
    FROM
      (SELECT a.*,
        row_number() OVER (ORDER BY OWNER ASC) rn,
        COUNT(1) over() mrn
      FROM (SELECT * FROM all_objects) a
    WHERE ROWNUM BETWEEN least(100,mrn) AND 150It is not very fast if I run that kind select from big table
    Any tips to optimize this query?
    Regards,
    Jari

    Hi,
    I'm so bad with SQL :(
    Here is sample where I need that kind query.
    http://actionet.homelinux.net/htmldb/f?p=100:504
    It looks standard Apex report but it is not.
    It is just test to use query to output html using htp package
    I send parameter start row, max rows, column I like order by.
    Now I do query for cursor
        /* Report query */
        l_sql := '
          SELECT * FROM(
            SELECT a.*, row_number() OVER (ORDER BY '
            || l_sort_col
            || ' '
            || l_sort_ord
            || ') rn, COUNT(1) over() mrn
            FROM(' || l_sql || ') a
          ) WHERE rn BETWEEN LEAST(' || l_start_row || ',mrn) AND ' || l_last_row
        ;Then I loop cursor and output html.
    You can order report by click heading and there is that pagination
    I did not know that I could find examples by "pagination query" =), thanks for that tip for both of you.
    I know Apex have reports ,
    but I need have features that Apex templates can not provide at least yet.
    So I have study that generating html tables using custom package instead Apex report should be best approach to get layouts I need.
    Regards,
    Jari
    Edited by: jarola on Jan 21, 2011 10:38 PM

Maybe you are looking for