Selecting TOP 20 Products per Catagory

Hi
I'm trying to select the TOP 20 Products per Catagory out of my Star Topology Database
if someone would PLEASE be able to help me out.
Here is my Query: -
SELECT Distinct (SELECT TOP 20 DP.[Description]), DP.Mims_Sub_Cat, SUM(FD.Cost) AS 'Cost'
FROM DIM_Product DP, FACT_Dispensary FD, DIM_Time DT, DIM_Client DC
WHERE DP.Product_KEY = FD.Product_Key
AND FD.Time_KEY = DT.Time_KEY
AND FD.Client_Key = DC.Client_KEY
AND DT.[Year] = 2007
AND DT.[Month] IN (2)
AND Client_name LIKE '%Medicare%'
AND DP.Manufacture_Name LIKE '%Cipla%'
--AND DP.[Description] IN (SELECT TOP 20 [Description])
AND DP.Mims_Sub_Cat IN (SELECT Mims_Sub_Cat)
GROUP BY DP.Mims_Sub_Cat, DP.[Description], FD.Cost
ORDER by DP.Mims_Sub_Cat, SUM(FD.Cost) DESC
My other problem is that it keeps on selecting the same products although i have a distinct in my query
The query will select a product with the amount and then select the same product again with a different amount.
 Example :-
Product Descripion               Catagory              Cost
ULTAK TABS 150MG 60    Acid Reducers    384.94
ULTAK TABS 150MG 60    Acid Reducers    85.54
ULTAK TABS 150MG 60    Acid Reducers    56.98

What about:
SELECT * FROM
SELECT DP.[Description], DP.Mims_Sub_Cat, SUM(FD.Cost) AS 'Cost',
RANK() OVER(PARTITION BY DP.Mims_Sub_Cat
ORDER BY SUM(FD.Cost)) AS RANKedColumn
FROM DIM_Product DP, FACT_Dispensary FD, DIM_Time DT, DIM_Client DC
WHERE DP.Product_KEY = FD.Product_Key
AND FD.Time_KEY = DT.Time_KEY
AND FD.Client_Key = DC.Client_KEY
AND DT.[Year] = 2007
AND DT.[Month] IN (2)
AND Client_name LIKE '%Medicare%'
AND DP.Manufacture_Name LIKE '%Cipla%'
AND DP.Mims_Sub_Cat IN (SELECT Mims_Sub_Cat)
) SUbquery
WHERE RankedColumn <=20
HTH, Jens K. Suessmeyer.
http://www.sqlserver2005.de

Similar Messages

  • Select top 10 rows for each product

    Hi,
    I have to build a query in the following way:
    I have a query like,
    select dept, product, product_sold
    from products
    order by 1, 2 desc
    But I have a requirement, not to show all the products in dept . I need to show only first 10 rows of each 'dept' column.
    Please help me in acheiving this.

    You would do something like this (untested):
    select dept
    , product
    , product_sold
    from (
       select dept
       , product
       , product_sold
       , row_number() over (
          partition by dept
          order by product
          , product_sold
       ) rn
       from products
    where rn <= 10;Assuming that I have correctly guessed the ordering you require...
    cheers,
    Anthony

  • SELECT TOP query in HANA

       Hi,
    Can somebody give me the HANA equivalent of the following SQL query:
    SELECT TOP (731-624+1) COLUMNNAME FROM TABLENAME
    In case of HANA, it gives syntax error near "(".

    Hi Yash,
    As per the HANA SQL syntax supported case is
    <select_clause> ::= SELECT [TOP <unsigned_integer>] [ ALL | DISTINCT ]
    <select_list>
    After Top only an unsigned intger is expected and cannot handle an <expression> like in your example.
    Hope this is useful.
    Best Regards,
    Ranjit

  • Select BOM as per lot size against planned quantity

    Dear all
                  i hav prob. releated select BOM as per lot size against planned quantity , suppose i hav monthly plnned order for
    1000 nos. quantity and having two alternative BOMs like lot size 0 to 500 and 0 to 200 , so after MRP run system should create planned order(inhouse prod.) as per lot size i.e. 500 x1 and 200x 2 ., how is it possible please guide me .
    thankx in advanced

    create a two production version , if the plan quantity is more than 200 system will take the Alternative BOM  and take the BOM ( 0-500 ) otherwise system will take the BOm ( lotsize 0-200).
    Or
    Create a Production version, Manually change the PV as per your requirement , And  rerun MRP with delete a recreate option
    regards,
    Sundaresan

  • Convert "select top 5 ..." in Oracle8i

    -- We are in the process of migrating application from SQLserver7 to Oracle8i,
    -- and trying to convert a procedure to return top 5
    -- rows given a search string.
    -- In SQLserver7, "select top 5 ... "
    -- The Oracle8i Application Developer's Guide - Fundamentals
    -- recommends to use rownum, the query runs OK in SQL*Plus,
    -- but gets error when used in a procedure with returned cursor.
    -- Is there any solution for it?
    -- Following is the sample query and procedure (in a package)
    -- Query returns top 5 rows
    select t.rank, t.productid, t.productname
    from (
    Select score(0) as rank, productid, productname
    from Product
    where status = 'A'
    and contains(productname, 'Frog', 0) > 0
    order by rank desc, productid
    ) t
    where rownum < 6;
    -- Proc Name: Pr_Test
    -- Purpose: Retrieve product data for a specified search string
    CREATE OR REPLACE PACKAGE pkg_test
    IS
    TYPE RT1 IS RECORD (
    Rank NUMBER(10),
    ProductID Product.ProductID%TYPE,
    ProductName Product.ProductName%TYPE
    TYPE RCT1 IS REF CURSOR RETURN RT1;
    PROCEDURE pr_test
    (i_searchstring IN VARCHAR2 ,
    io_prdcursor IN OUT RCT1);
    END pkg_test;
    CREATE OR REPLACE PACKAGE BODY pkg_test
    AS
    PROCEDURE pr_test
    (i_searchstring IN VARCHAR2 ,
    io_prdcursor IN OUT RCT1)
    IS
    BEGIN
    OPEN io_prdcursor FOR
    select t.rank, t.productid, t.productname
    from (
    Select score(0) as rank, productid, productname
    from Product
    where status = 'A'
    and contains(productname, i_searchstring, 0) > 0
    order by rank desc, productid
    ) t
    where rownum < 6;
    END pr_test;
    END pkg_test;
    -- Following is the error message when compiling the package body:
    Warning: Package Body created with compilation errors.
    SQL> show error
    Errors for PACKAGE BODY PKG_TEST:
    LINE/COL ERROR
    19/7 PLS-00103: Encountered the symbol "ORDER" when expecting one of
    the following:
    ) * & - + / mod rem with an exponent (**) and or group having
    intersect minus start union where connect &#0124; &#0124;
    The symbol ")" was substituted for "ORDER" to continue.
    20/11 PLS-00103: Encountered the symbol ")" when expecting one of the
    following:
    . ( , * @ % & - + ; / for mod rem an exponent (**) asc desc
    &#0124; &#0124;
    -- Run the procedure and get the results
    declare
    i number := 0;
    v_string varchar2(50) := 'CAT';
    -- v_string varchar2(50) := 'FROG%';
    v_RC1 pkg_test.RCT1;
    v_Score NUMBER(10);
    v_ProductID Product.ProductID%TYPE;
    v_ProductName Product.ProductName%TYPE;
    begin
    pkg_test.pr_test (v_string, v_RC1);
    LOOP
    FETCH v_RC1 INTO v_Score,v_ProductID,v_ProductName;
    EXIT WHEN (v_RC1%NOTFOUND);
    DBMS_OUTPUT.put_line(substr('Score='&#0124; &#0124;v_score&#0124; &#0124;', ProdID='&#0124; &#0124;v_ProductID ,1,255));
    i := i + 1;
    END LOOP;
    DBMS_OUTPUT.put_line('Total '&#0124; &#0124;i&#0124; &#0124;' records retrieved.');
    end;
    null

    http://www.orafaq.org/faqsql.htm#TOP
    This may be of use, the plsql cursor declaration syntax may not have all the facilities of runnning the query from sqlplus:
    How does one select the TOP N rows from a table?
    Form Oracle8i one can have an inner-query with an ORDER BY clause. Look at this example:
    SELECT *
    FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC)
    WHERE ROWNUM < 10;
    Use this workaround with prior releases:
    SELECT *
    FROM my_table a
    WHERE 10 >= (SELECT COUNT(DISTINCT maxcol)
    FROM my_table b
    WHERE b.maxcol >= a.maxcol)
    ORDER BY maxcol DESC;
    Turloch

  • 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

  • Multiple Selection of Products in Sales Order

    Hi Experts,
    my requirement is to select mulitiple products from the product F4 help pop-up in sales order items assignment block. To achieve this I have made the following settings:
    1.added the following code in SearchHelpResult.htm view layout of PRD01QR/SearchHelpResult.
                          onRowSelection        = "<%= lv_select_event %>"
                          selectionMode         = "<%= RESULT->SELMODE_MULTI %>"
                          selectedRowIndex      = "<%= RESULT->SELECTED_INDEX %>"
                          selectedRowIndexTable = "<%= RESULT->SELECTION_TAB %>"
    after this settings, I am able to select multiple products.
    2.I have created a button (Choose) for the component PRD01QR to transfer the products to the items assignment block.
    please suggest me on how to transfer the multiple products from the Pop-up to the items assignment block (BT115IT_SLSO)and create line items using the events.
    thanks and regards,
    S Reddy

    Hi,
    Redefine the method EH_ONSELECT_ORDERED_PROD.
    As you can see, they are getting the current entity,reading the Product GUID and setting it.
    Here is sample code snippet...
      DATA:  lr_context_node    TYPE REF TO cl_bsp_wd_context_node,
                  lr_cw                   TYPE REF TO cl_bsp_wd_collection_wrapper,
                  lr_it                     TYPE REF TO if_bol_bo_col_iterator,
                 lr_current              TYPE REF TO if_bol_bo_property_access,
                 lr_prd                   TYPE REF TO if_bol_bo_property_access,
                 lr_product_guid      TYPE REF TO comt_product_guid,
                 lv_outbound_plug   TYPE seocmpname,
                 lv_index                type sy-index.
      TRY.
       Check outbound plug
          lv_outbound_plug = prodsearch_popup->get_fired_outbound_plug( ).
          CHECK lv_outbound_plug = 'RETURNRESULT'.
          lr_context_node = prodsearch_popup->get_context_node( iv_cnode_name = 'PRD' ).
          lr_current = lr_context_node->collection_wrapper->get_first( ).
         while lr_current is bound.
        set product guid
          lr_product_guid ?= lr_current->get_property( iv_attr_name = 'PRODUCT_GUID' ).
          lr_cw      = get_collection_wrapper( gc_context_node_admini ).
          lr_it      = lr_cw->get_iterator( ).
          lv_index = lv_index + 1.
          lr_prd    = lr_it->get_by_index( iv_index = lv_index ).
          lr_prd->set_property( iv_attr_name = 'PRODUCT' iv_value = lr_product_guid->* ).
         lr_current = lr_context_node->collection_wrapper->get_next( ).
        CATCH cx_sy_ref_is_initial cx_sy_move_cast_error.
          RETURN.
      ENDTRY.
    Basically you have to loop at the products and populate admini.
    Regards,
    Masood Imrani S.

  • CONTRIBUTION MARGIN (PLAN) CALCULATION FOR PRODUCTS (PER UNIT, LOCATION WIS

    Requirement of a Report to calculate Contribution Margin (Plan) - For Calculating Contribution Margin.
    2 Key figures need to be arrived (per unit/cv of product, locationwise) are Net Sales Realisation (NSR) and Total Variable Cost (TVC).
    a) To arrive at NSR (Plan), all the combinations of upcoming discounts and Free Goods schemes which are going to be in force for the coming month for a product, need to be adjusted in the Net Sales Value to get NSR value per unit of Product (SKU / CV), locationwise
    The NSR is the result of adjusting Discounts, Excise and Schemes to the List price of a product.
    b) TVC is the result of adding Total Material Cost(TMC) + [(LabourPower) conversion cost]Freight.
    Calculation of material cost takes into account the LCC (Landed cost chart) price of the materials, which is a future price.
    The Total variable Manufacturing Cost (TMC+Conversion cost) can be calculated using Costing Run (CK40N), using LCC price.
    In COPA Reporting the values like List price, Discounts, Excise, Free Goods Schemes and freight flows from Billing Documents (SD) because of condition types mapping in to value fields in COPA, which are components for calculating NSR (Actual), based on the Actual sales.
    We want to understand how do the Plan values (List price, Discounts, Excise, Free Goods Schemes and freight) per unit of Product, location wise, flow to the Value fields in COPA Planning,  so that the Contribution Margin (Plan) can be calculated for each product per unit , location wise.
    Contribution Margin = NSR u2013 Total Variable Cost.

    Then you hit a bug in your version of Oracle. You may want to investigate and update to a newer version. I get the following error when trying to register your schema in 10.2.0.1
    ORA-31154: invalid XML document
    ORA-19202: Error occurred in XML processing
    LSX-00246: invalid QNAME "***_voting_flag"
    This error is consistent with Spy 2008 as well (I didn't try Xerces but I've got two that agree so it's good for me).

  • I have just upgraded to 10.6.7, and was browing the App. Store, I selected a product and it started to download, I cancelled the download, but it still registers in my purchases list, have I purchased that appl. and how can I cancel the purchase?

    I have just upgraded to 10.6.7, and was browing the App. Store, I selected a product by mistake and it started to download, I cancelled the download, but it still registers in my purchases list, have I purchased that appl.? and how can I cancel the purchase in my purchases list?

    I think that as soon as you click "Buy" and type in your details, the iTunes server is alerted that you have bought the item, even if it hasn't downloaded. Your "purchased" list is based on your account and not your computer so I'm afraid even if you haven't completed the download, you will be charged for it (but if you do now download it, you won't be charged again). This also means that you can't remove items from the purchased list.
    Glad to be of help (I hope),
    Jonathan

  • Sequence Selection in Production Order

    Hi All,
    I am having following problem related to the sequence selected in production order...
    In my scenario there are multiple sequences in a routing for a material.In the production Order Type I have made setting of manual selection of sequence while creation of production order.When I create production order the system ask for selection of the alternate sequence and after selecting the alternate sequence the system copies all the data related to that sequence <b>But</b> when I go and see the operation overview the system still displays the standard sequence. How can I correct this problem because when I am doing confirmation the system throws error message than the standard sequence 0 does not exist.
    Please help me correct this problem.
    Regards,
    Anup Dubey

    Hi,
    As i have mentioned the system is asking me select alternate sequence it means that the tick is there.
    Please lemme know why the system is displaying the standard sequenec in operation overview though all the details related to operation are of alternate sequence.
    Regards,
    Anup Dubey

  • How to select top one in CDS view ?

    I have tried following logic to select top one in CDS view but its giving error -
    define view Cds_View_First_Reference as select  top one CReferredObject from CDSVIEWCROSSREF

    Hi Ruchi,
    since you posted this question in "ABAP in Eclipse" I assume you are asking about CDS in ABAP. This is important because the CDS features sets in ABAP and (native) HANA are different.
    Be that as it may,, SELECT TOP 1 is neither supported in the CDS implementation in ABAP nor in HANA.
    In ABAP you might consider using the min() or max() function together with the appropriate GROUP BY clause in the CDS view (depending on what you want to achieve), but you can also easily "implement" this in the Open SQL statement which selects from your CDS view.
    Using the additions SELECT SINGLE or UP TO 1 ROWS and an appropriate ORDER BY clause in Open SQL, you can achieve the same as SELECT TOP 1.
    Unfortunately there is currently no possibility to define a view which delivers the TOP 1 which you can again use in another view ("view on view").
    Kind regards
    Chris

  • When installing acrobat XI pro the 'select a product' drop down menu does not include my product?

    when installing acrobat XI pro the 'select a product' drop down menu does not include my product?

    For future reference... if you have the trial version installed and plan to buy it after trying it out, there is no need to uninstall it.  It can be activted to full use with the serial number from your purchase.
    You should still be able to download and install the trial version and use your serial number to activate it.  For the direct download link to the trial below, be sure to follow the steps outlined in the Note: Very Important Instructions section on the download pages at this site or else the download will not work properly.
    http://prodesigntools.com/adobe-acrobat-xi-pro-standard-reader-direct-download-links.html

  • Select multiple Products at a time

    Hi,
    While creating a new Sales Order in CRM, when you press F4 on Product ID field, we get multiple products on search help screen. we can select only one at a time.  But requirement is to select multiple Products at a time and they need to be copied to the sales order at item level. How to acheive this?

    Hi ,
      After enhancing the view update the below piece of code.There it will be selmode_single u change that value for multiple selection.
    typed_context->Your context Node->set_selection_mode( iv_selection_mode = cl_bsp_wd_context_node_tv=>selmode_multiedit ).
    Rg,
    gobi

  • Prepared Statement, executing  SELECT TOP in Ms Access

    I'm having the following problem. I built an application fetching data without any problem from MS SQL Server, this was using prepared statements. Now i'm having this strange problem with the following query:
    SELECT TOP 1 *
    FROM table
    WHERE appliance_id = ?
    AND ttimestamp_initpk <= ?
    AND ((Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?))
    ORDER BY ttimestamp_initpk DESC
    While on SQL Server this fetches just a record, on MS Access it fetches the whole set of records without worrying about TOP instruction.
    That is, it acts like a SELECT * FROM, and this slows down runtime behaviour.
    I'm using sun.jdbc.odbc.JdbcOdbcDriver, is it the problem?
    Thanks, Mirko

    Thanks for your answer, but i'm not sure this is the reason.
    I made one more test: i wrote a .Net application connecting to a MS Access using an ODBC connection. SELECT TOP statement is working fine, so i think i'll try another JDBC driver. Any other solution??
    Thanks,
    Mirko

  • ALTERNATIVE FOR 'SELECT TOP STATEMENT

    HI FRIENDS
    IF ANY ONE KNOWS HOW TO CONVERT THE SQL STATEMENT GIVEN BELOW PLEASE HELP ME
    SELECT TOP 1 CardID FROM EasyRechargeMaster WHERE CardGroup = EasyRecharge.CardGroup
    THANKS & REGARDS

    Check this query. It should give you desired results....Are you sure about that? Does TOP 1 mean "whatever happens to be the first row fetched"?

Maybe you are looking for

  • ISE 1.2 backup restore questions

    Hi all, I have been looking at the backup and restore procedure for ISE deployments and have to say I have found the documentation to be somewhat confusing in general. Whilst I get the gist of it I have found numerous areas that are grey. This questi

  • Help required in  webclient and crm report integration

    Hi , how to integrate webclient and CRM reports in CRM 2007 UI. i dont have much idea in this area.My requirement is integrating CRM report and webclient.But i dont know where to find report adn how to link the report to webclient. Please anyone help

  • [SOLVED] Pacman is broken on fresh installation

    I've just performed a fresh installation that seemed to go fine, following the Official Arch Linux Install Guide.  However, I get the following during my first login: Arch Linux 2.6.39-ARCH (myhost) (tty1) myhost login: root Password: [root@myhost ~]

  • Cisco WLC5508 Dynamic VLAN assignment error

    Hi All, We have a HA (SSO) WLC controller pair in two DC's with the Management Interface managing the AP's. The AP's are located in the Campus LAN and the Campus and DC networks are seperated by a L3 boundary. The plan is for one of the WLAN's to pro

  • When trying to download Acrobat XI, in the Adobe Application Manager, I get a download error

    It says I should contact customer care, so I am. Please help! Need to download Acrobat XI.