Selecting top 10 rows based on one column.

Hi,
I need to display the top 10 records for each distinct value of a column. 

USE Northwind;
-- Solution 1
SELECT S.SupplierID, S.CompanyName, CA.ProductID, CA.UnitPrice
FROM dbo.Suppliers AS S
  CROSS APPLY
    (SELECT TOP (10) *
     FROM dbo.Products AS P
     WHERE P.SupplierID = S.SupplierID
     ORDER BY UnitPrice DESC, ProductID DESC) AS CA
ORDER BY S.SupplierID, CA.UnitPrice DESC, CA.ProductID DESC;
-- Solution 2
WITH C AS
  SELECT S.SupplierID, S.CompanyName, P.ProductID, P.UnitPrice,
    ROW_NUMBER() OVER(
      PARTITION BY P.SupplierID
      ORDER BY P.UnitPrice DESC, P.ProductID DESC) AS RowNum
  FROM dbo.Suppliers AS S
    JOIN dbo.Products AS P
      ON P.SupplierID = S.SupplierID
SELECT SupplierID, CompanyName, ProductID, UnitPrice
FROM C
WHERE RowNum <= 10
ORDER BY SupplierID, ProductID DESC, UnitPrice DESC;
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • Formating the Row Based on one column value

    Hi Friends
    I am trying to format the Entire row based on the value of the first column in my Answers.
    Example if first column value in 'F' now i want the Entire row to be colored
    I can do conditional formating on one column but i want to do it on the entire row
    F     8.1 %     12.0 %
    E     5.2 %     3.5 %
    M     2.3 %     3.3 %
    If any one has done this or any suggestions please respond
    Thanks
    Sang

    Its a Pivot View
    F 8.1 % 12.0 %
    E 5.2 % 3.5 %
    M 2.3 % 3.3 %
    the column 1 --> F,E,M are the Product
    the column 2 --> 8.1% , 5.2% , 2.3% are the sales in year 2008
    the column 3 --> 12.0 % , 3.5 %, 3.3 % are the sales in year 2009
    So will i be able to apply the formating in pivot view based on one column to other column If yes please let me know how or
    suggest if this can be done using the BI Office , or BI publisher
    sing the BI Office i can do the formating in Excel but once i refresh the data all the formating is gone ... :(
    I am donno BI Publisher if we have to use BIP please suggest any solution its very very very urgent and important report formating they need here ....
    Thanks in advance David
    sango

  • Selecting rows based on one column change

    Hi All -
    I need to select the rows from a table (this table has 4 columns and has a primary key and have many records for that primary key).
    I need to select all the rows for this primary key for which only one column (in this case "flag" column) has been changing from its past value.
    How can I do this?
    for example, table data is:
    ID, flag, Profile,date
    pk, Y, Profile4,01/10/10
    pk, N, Profile4, 01/08/10
    pk,N, Profile3, 01/07/10
    pk,Y, Profile3, 01/05/10
    pk,Y, Profile2, 01/03/10
    pk,N, Profile1, 01/02/10
    The output of the query I am looking for should return the following i.e. only retrieve rows whose previous flag value has been changed:
    ID, flag, Profile,date
    pk, Y, Profile4,01/10/10
    pk,N, Profile3, 01/07/10
    pk,Y, Profile2, 01/03/10
    pk,N, Profile1, 01/02/10
    Please share your expertise.
    Thanks,
    Seenu

    Hi, Seenu,
    Centinul wrote:
    It is always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
    Seenu001 wrote:(1) Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bi
    PL/SQL Release 10.2.0.3.0 - Production
    CORE 10.2.0.3.0 Production
    TNS for Solaris: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production Good!
    (2) select 'pk' id,'Y' flag,'Profile4' profile,to_date('01/10/10','mm/dd/yy') dt from dual union all
    select 'pk','N','Profile4',to_date('01/08/10','mm/dd/yy') from dual union all
    select 'pk','N','Profile3',to_date('01/07/10','mm/dd/yy') from dual union all
    select 'pk','Y','Profile3',to_date('01/05/10','mm/dd/yy') from dual union all
    select 'pk','Y','Profile2',to_date('01/03/10','mm/dd/yy') from dual union all
    select 'pk','N','Profile1',to_date('01/02/10','mm/dd/yy') from dualNot bad. It can be made into a CREATE TABLE AS statement without a lot of work, but if you're not willing to do that little bit or work, why should anyone else?     
    (3) Expected output: I want all the rows from this table where the flags have been changed from its previous value.That's a vague description. Post the exat output, like Solomon did:
    ID F PROFILE  DT
    pk N Profile1 01/02/2010
    pk Y Profile2 01/03/2010
    pk N Profile3 01/07/2010
    pk Y Profile4 01/10/2010
    (4) I want all the rows from this table where the flags have been changed from its previous value.That's a repeat of the vague description. Explain how you get the crorrect results, with specific examples, like this:
    "The row dated January 2 should be included, because it is the oldest row in the table, regardless of what its flag is.
    The row dated January 3 should be included because ...
    The row dated January 5 should *not* be included, because ..."
    You don't have to explain every row, just every reason.
    Solomon - I tried your query but the prev_flag is not being populated, it shows null value '-'NULL is not the same as '-'. Did you issue a command like
    SET NULL "-"that would display a '-' instead of NULL?
    Solomon's query works fine for me, as it did for him. Post your code, even if you just copied it from this site. (There may have been an editing problem.)
    Frank - I tried your query, prev_flag is populated in this case but when I am using with the WITH clause, I am getting an error saying "unsupported column aliasing" , I guess WITH command doesnt allow use of column alias. The problem is that I forgot the keyword AS after the sub-query name.
    WITH     got_prev_flag     AS
         SELECT     id, flag, profile, dt     -- DATE is not a good column name
         ,     LAG (flag, 1, '??') OVER (ORDER BY dt)  AS prev_flag
         FROM     t
    --     WHERE     ...     -- any filtering goes here
    SELECT     id, flag, profile, dt
    FROM     got_prev_flag
    WHERE     flag     != prev_flag
    ;If you don't post data in an executable form, then people can't test their ideas. If people can't test their ideas, trivial mistakes like this are very likely.
    This flag column will have either
    Y or N columns. Could you tell me what is the use of "??" value.By default, LAG returns NULL for the first row. If you want to include the first row in the results, then "WHERE     flag     != prev_flag" won't work when prev_flag is NULL. We could explicitly check for "prev_flag IS NULL", but I find it cleared to override the default, and have LAG return '??' on the first row. I guessed that '??' would make the condition "WHERE     flag     != prev_flag" work, no matter what value flag had. There's nothing magical about '??'; you can use any string that will never actually match flag.

  • Unique row based on two columns and single column

    Dear Members,
    I have a table which contains duplicate rows, for which a query should be able to fetch the unique row from the table. Here the unique is not based on one column, but it should be on two columns and also check for uniqueness on one column.
    create table addr ( firstname varchar2(10), lastname varchar2(10), area varchar2(3));
    insert into addr values('bob', 'james', '1');
    insert into addr values('bob', 'james', '1');
    insert into addr values('harry', 'bert', '1');
    insert into addr values('jimmy', 'bert', '1');
    insert into addr values('sam', 'mac', '1');
    insert into addr values('sam', 'knight', '1');
    insert into addr values('tom', 'sand', '1');
    insert into addr values('cat', 'mud', '1');
    The output of query should contain 3 rows.
    bob - james
    harry - bert or jimmy - bert [ either one of them, but not both ]
    sam - mac or sam - knight [ either one of them, but not both ]
    tom - sand
    cat - mud
    SELECT firstname, lastname as total from addr WHERE area = '1' GROUP by firstname,lastname; This does not take of single column duplication..
    Any suggestions..

    SQL> with t_data
    as
    select 'bob' as firstname, 'james' as lastname, '1' as area from dual union all
    select 'bob', 'james', '1' from dual union all
    select 'harry', 'bert', '1' from dual union all
    select 'jimmy', 'bert', '1' from dual union all
    select 'sam', 'mac', '1' from dual union all
    select 'sam', 'knight', '1' from dual union all
    select 'tom', 'sand', '1' from dual union all
    select 'cat', 'mud', '1' from dual
    SELECT
            firstname,
            lastname,
            area
    FROM
                    SELECT
                            t.*,
                            row_number() over(partition BY firstname order by 1) rn,
                            row_number() over(partition BY lastname order by 1) rn1
                    FROM
                            t_data t
    WHERE
            rn     = 1
    AND rn1 =1 ; 
    FIRSTNAME       LASTNAME        AREA
    bob             james           1
    cat             mud             1
    jimmy           bert            1
    sam             knight          1
    tom             sand            1
    SQL>

  • Deleting duplicate rows based on three columns in Oracle 8i

    Hi all,
    The database we use is Oracle 8i.
    The query below raises the too_many_rows exception when I launch an application. So I want to delete the duplicated rows :
    select polarisation_1, polarisation_2
    into v_pol1_tech, v_pol2_tech
    from v_cfh_lien_element
    where nom_lien = p_nom_lien
    AND num_canal_1 = p_num_canal_1
    AND freq_emise_1 = p_freq_emise_1;
    Notice that with many possible values of the parameters p_nom_lien, p_num_canal_1 and p_freq_emise_1 then the exception is raised.
    So how to delete generally the duplicated rows based on the three columns "nom_lien" , "num_canal_1" and "freq_emise_1" ?
    Thank you very much indeed.

    Check the other thread with same question deleting duplicate rows based on three columns in Oracle 8i

  • Join all rows bases on one column value

    Hi All,
    I have requrement like Join all rows bases on one column value, i am not getting how to accomplish that. Here is my requrement. i have table test(id,id_desc) with no key
    table:Test
    id id_desc
    1 desc_a
    1 desc_b
    1 desc_c
    Now the requremnet i have one more table as test1(id,id_desc) here id is primary key. where record i need to insert as
    id id_desc
    1 desc_a
    desc_b
    desc_c

    orza wrote:
    Hi All,
    I have requrement like Join all rows bases on one column value, i am not getting how to accomplish that. Here is my requrement. i have table test(id,id_desc) with no key
    table:Test
    id id_desc
    1 desc_a
    1 desc_b
    1 desc_c
    Now the requremnet i have one more table as test1(id,id_desc) here id is primary key. where record i need to insert as
    id id_desc
    1 desc_a
    desc_b
    desc_cI'm guessing you want to pivot the results in TEST and use that to insert into TEST1?
    If so this may be useful
    http://www.oracle-base.com/articles/misc/StringAggregationTechniques.php

  • Delete duplicate rows -- based on 4 columns -- how?

    I asked this question on how to delete duplicates recently and received this suggestion which works well -- except --
    With CTE AS
    SELECT *, ROW_NUMBER() OVER (Partition by fld1 order by fld1) RowNum
    FROM #tmpA
    DELETE From CTE
    WHERE RowNum > 1
    -- the actual table I need to delete duplicate rows on is based on 4 columns.  The following table contains 14,462 rows of which 14,348 are distinct -- based on the following 4 colums.  Below is an image of a sample of the data contained in the
    table for my question and to the right of that data is the column structures (data types).  Is it possible to do something like the above example suggestion with the table in the image below?  How to do that?  I need to delete rows so that 14462
    goes down to 14348.  If I only reference one column for the delete -- this would delete like 7000+ rows.  I only need to remove 114 rows.
    Rich P

    Add the other 3 columns to the partition.
    Jason Long

  • How to split the data based on one column

    Dear All,
    I have the table data like this.
    type quantity revenue_mny count country
    a 10           10          2 India
    a 20          12          3 India
    b 30          15          1 India
    a 35          20          2 US
    b 20          10          1 US
    b 60          15          1 US
    I woulkd like to split the date based on type column.
    For each country, for Type "a" get the sum of revenue count quanity ans same for b
    and all shuld come in on row for each country.
    output should be like
    country revenue_mny(For a) quantity(for a) count(For a) revenue_mny(for b) quantity(for b) count(For b)
    India 22 30 5 15 30 1
    US 20 35 2 25 80 2
    I tried the below query . its not splittng the date for each country in one row.
    select country,
    sum(case when type='a') then revenue_mny else 0 end ) revenue_mny_a,
    sum(case when type='b' then revenue_mny else 0 end ) revenue_mny_b
    sum(case when type='a' then quantity else 0 end) quantity_a,
    sum(case when type='b' then quantity else 0 end) quantity_b from
    test
    group by country
    Please need your helo

    Like this?
    with t as
    select 'a' type, 10 quantity, 10 revenue_mny, 2 cnt, 'India' country from dual union all
    select 'a', 20, 12, 3, 'India' from dual union all
    select 'b', 30, 15, 1, 'India' from dual union all
    select 'a', 35, 20, 2, 'US' from dual union all
    select 'b', 20, 10, 1, 'US' from dual union all
    select 'b', 60, 15, 1, 'US' from dual
    select country,
    sum(case when type='a' then revenue_mny else 0 end ) revenue_mny_a,
    sum(case when type='a' then quantity else 0 end) quantity_a,
    sum(case when type='a' then cnt else 0 end) cnt_a,
    sum(case when type='b' then revenue_mny else 0 end ) revenue_mny_b,
    sum(case when type='b' then quantity else 0 end) quantity_b ,
    sum(case when type='b' then cnt else 0 end) cnt_b
    from t
    group by country;result:
    COUNTRY  REVENUE_MNY_A QUANTITY_A CNT_A REVENUE_MNY_B QUANTITY_B CNT_B
    India    22            30         5     15            30         1
    US       20            35         2     25            80         2Or you can do it with a decode instead of case. The result will be the same:
    with t as
    select 'a' type, 10 quantity, 10 revenue_mny, 2 cnt, 'India' country from dual union all
    select 'a', 20, 12, 3, 'India' from dual union all
    select 'b', 30, 15, 1, 'India' from dual union all
    select 'a', 35, 20, 2, 'US' from dual union all
    select 'b', 20, 10, 1, 'US' from dual union all
    select 'b', 60, 15, 1, 'US' from dual
    select country,
    sum(decode(type,'a',revenue_mny,0)) revenue_mny_a,
    sum(decode(type,'a',quantity,0)) quantity_a,
    sum(decode(type,'a',cnt,0)) cnt_a,
    sum(decode(type,'b',revenue_mny,0)) revenue_mny_b,
    sum(decode(type,'b',quantity,0)) quantity_b,
    sum(decode(type,'b',cnt,0)) cnt_b
    from t
    group by country;(I changed tablename from TEST to T and columnname from COUNT to CNT, because you should not use reserved words as tablename or columnname.)
    Edited by: hm on 09.10.2012 06:17

  • How to select/unselect all checkbox in one column

    Hi Experts,
    I have a report with a column as check box. The query is like:
    select apex_item.checkbox(1, ID) "update", ID, name, job
    from a_table
    So that user can select the rows they want to update.
    Sometimes user wants to select all the rows. It's not easy to select all the rows one by one when there are many rows on the report.
    So how to select/unselect all rows in this case?
    Thanks,
    Daniel

    Hi,
    See if this post help
    Re: Need Check All in Checkbox
    Regards,
    Jari

  • Select top row in Single Query?

    Hi
    Can somebody help me to write a query to get the first row after order by clause using single query alone.
    Example:
    I can write following query to select first row
    select * from (selec * from t order by col1) where rownum = 1;
    But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
    Please help me.

    Raghav.786 wrote:
    Hi
    Can somebody help me to write a query to get the first row after order by clause using single query alone.
    Example:
    I can write following query to select first row
    select * from (selec * from t order by col1) where rownum = 1;
    But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
    Please help me.
    What Oracle version are you?
    If you have 12c you can use
    select col1,...
      from t
    order by col1
    fetch first 1 row only;
    If less than 12c, you have can't do it without a subquery.
    What are you actually trying to do? Read Re: 2. How do I ask a question on the forums?
    and follow the advice there by giving example create table and insert sample data statements and
    explaining clearly what you are trying to do. Then we can help more.

  • Need to  color a Table row based on a Column value

    Dear Alll
    I have a requirement to color the rows of a table based on a column value in it. I have tried and surfed many useful materials over the net. but none of them solves my purpose. Please help me, I know that i can used OADataBoundValueViewObject and create a custom css file and apply color to a particular column of a table using a decode in the select statement of that VO.
    But all i need is to color a particular row with a particular color. Need your help with this ........
    Please do reply
    Best Regards
    Edited by: Antony Jayaraj on Mar 27, 2012 8:54 PM

    These posts might help you.
    How to change the row color based on Condition
    Can we colour the rows in the column of a table
    Regards,
    Peddi.

  • Inserting multiple selection from checkbox in to one column of the database

    Hi,
    how to insert multiple selection from checkbox into one column of the database.(I select array of values from checkbox ,then how to insert tat array of values iinto single column name).
    Anyone can u reply me
    Thanx

    hhhmmm.... is this what you mean?
    lets say you hava a checkbox1 with values value1, value2, value3 and you selected all there of them? then you want then to be stored in the database in one column?
    now the question is:
    Is it going to be one column one row?
    datafield
    value1,value2,value3
    Or one column multiple row?
    datafield
    value1
    value2
    value3
    Which is it?

  • How not show duplicate rows based on one field

    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0
    Hello
    I have a query that looks for certain scripts that did not run on a particular day compared to what ran the same day a week ago. We want to include the start_datetime and end_datetime but when I add it to the select statement it brings up all instances of the jobs that run multiple times during the day. Is there a way to exclude the extra rows based on the script_name field?
    SELECT instances.script_name,
                             instances.instance_name,
                             REGEXP_REPLACE(master.description,
                                            chr(49814),  -- em-dash
                                            '-') description
                                            --instances.start_datetime
                      FROM   xxcar.xxcar_abat_instances Instances,
                             xxcar.xxcar_abatch_master  Master
                      WHERE  1 = 1
                      AND    TRUNC(start_datetime) = TRUNC(TO_DATE(:p_StartDate, 'YYYY/MM/DD HH24:MI:SS')) - (:p_NumOfWeeks * 7)
                      AND    Instances.SCRIPT_NAME = Master.SCRIPT_NAME (+)
                      MINUS
                      SELECT script_name,
                             instance_name,
                             NULL
                             --NULL
                      FROM   xxcar.xxcar_abat_instances
                      WHERE  1 = 1
                      AND    TRUNC(start_datetime) = TRUNC(TO_DATE(:p_StartDate, 'YYYY/MM/DD HH24:MI:SS'))

    MINUS does a set operation - removing rows from the first set that exactly match the second set.
    When you add columns to the first set, you want a more restricted filtering - try a multi-column NOT IN:
    To remove multiple runs, group and get min/max
    SELECT instances.script_name,
                             instances.instance_name,
                             REGEXP_REPLACE(master.description,
                                            chr(49814),  -- em-dash
                                            '-') description,
                             min(instances.start_datetime) start_datetime,
                             min(instances.end_datetime) end_datetime
                      FROM   xxcar.xxcar_abat_instances Instances,
                             xxcar.xxcar_abatch_master  Master
                      WHERE  1 = 1
                      AND    TRUNC(start_datetime) = TRUNC(TO_DATE(:p_StartDate, 'YYYY/MM/DD HH24:MI:SS')) - (:p_NumOfWeeks * 7)
                      AND    Instances.SCRIPT_NAME = Master.SCRIPT_NAME (+)
                      AND (script_name, instance_name) NOT IN
                    ( SELECT script_name,
                             instance_name
                      FROM   xxcar.xxcar_abat_instances
                      WHERE  1 = 1
                      AND    TRUNC(start_datetime) = TRUNC(TO_DATE(:p_StartDate, 'YYYY/MM/DD HH24:MI:SS'))
    group by instances.script_name, instances.instance_name, master.descriptionYou didn't give table definitions, and the query has schemas in it, so I didn't test it.
    regards,
    David

  • Selecting top row after sorting

    hi,
    i have a table emp, whose primary key is empid(varchar2),
    i want to sort the empid and select the top row after sorting,
    i can sort the table using "select * from emp order by empid desc,
    i can select the top row using "select * from emp where rownum=1"
    i want a combination of the 2,
    pls provide me the required query
    Thanks and Regards,
    Saurabh Jhunjhunwala

    SEELCT *
       FROM ( SELECT e.*
                               , ROWNUM  row_num
                       FROM emp e
                     ORDER BY empid desc
    WHERE row_num =  1Regards
    Arun

  • Deleting duplicate entries based on one column

    Guys,
    I have two internal tables i_tab1 and i_tab2.
    I want to copy contents of i_tab1 into i_tab2 while removing any duplicate entry.
    i am comparing on just one column in i_tab1.

    Hi,
        Try this way
    LOOP AT itab2 INTO wa_itab2.
    READ TABLE itab1 INTO wa_itab1 WITH KEY field = wa_itab1-field BINARY SEARCH.
    IF sy-subrc = 0.
    code
    MODIFY itab2 INDEX sy-tabix FROM wa_itab2 TRANSPORTING field. " field is modified field
    ENDIF.
    ENDLOOP.
    Regards
    Bala Krishna

Maybe you are looking for