Need SQL for below scenerio .

Hi Experts,
Consider an Order Table with the following table structure with some Sample Data:
ORDER_DAY
ORDER_ID
PRODUCT_ID
QUANTITY
PRICE
01-JUL-11
O1
P1
5
5
01-JUL-11
O2
P2
2
10
01-JUL-11
O3
P3
10
25
01-JUL-11
O4
P1
20
5
02-JUL-11
O5
P3
5
25
02-JUL-11
O6
P4
6
20
02-JUL-11
O7
P1
2
5
02-JUL-11
O8
P5
1
50
02-JUL-11
O9
P6
2
50
02-JUL-11
O10
P2
4
10
Need  SQL to get all products that got sold both the days and the number of times the product is sold.
Desired output :
PRODUCT_ID
COUNT
P1
3
P2
2
P3
2
Thanks and Regards,
Sumanth Kulkarni

Hi,
SumanthKulkarni wrote:
Hi
I tried below approach , but i didnt get desired output for P1
select count(s) a,product_id  from
(select count(product_id) s,order_day ,product_id from orders group by order_day,product_id
order by product_id asc) t
group by product_id
having count(s) >1
Thanks and Regards
Sumanth Kulkarni
Run the sub-query by itself, and look at the results.  You should see something like this:
         S ORDER_DAY   PRODUCT_ID
         2 01-JUN-2011 P1
         1 02-JUN-2011 P1
         1 01-JUN-2011 P2
When you're computing the column a for the final output, do you want to count how many rows of this result set have product_id='P1'?  That's what COUNT does, but I don't think that's what you want.
Do you want to add up the numbers in the S column?  Then use SUM (s), not COUNT (s).
You could also do the whole job without a sub-query, like this:
SELECT    COUNT (*)    AS a
,         product_id
FROM      orders
GROUP BY  product_id
HAVING    COUNT (DISTINCT order_day)  > 1

Similar Messages

  • Need solution for below requiernment

    Hi,
    Please tell me flow logic for below requiernment:
    1.     Read actual payroll period from T569V for ABKRS set in infotype 0001
    2.     Read actual payroll result from cluster RD using german standard functions
    3.     Loop through table RT and check for wagetype 9000
    4.     create a batch-input to infotype 0015 wagetype 9000
    ANZHL = 1
    ZEINH = piece
    BEGDA = actual month - 1 (e.g. actual month 06/2008 enter 01.05.2008)
    5.     allow option for direct or delayed start of batchinput
    My confusion is: 1) Why do we need to Read actual payroll period from T569V for ABKRS set in infotype 0001.
    2) To update IT 0015 , do we need to write a BDC or we can use FM HR_INFOTYPE_OPERATIONS.
    regards

    hi,
    1.this requirement may be cause of mid year go live in the past.
    2. BDC for IT 15 makes sense as it is easier to maintain a BDC  program.
    Regards
    Sameer.

  • Need Sql for terda data database

    Can any one help send me the sql for teradata database. for creating the variables. I need to create variables for Last month begin date and last month end date.

    I am trying this tera data Sql this is for curent month date.
    select cast(current_date as date) - (extract (day from cast(current_date as date)) - 1) + interval '1' month - 1
    I need tera data sql for Last month begin date and last month end date. I searched various forums but could not get the answer. Any suggesstions please.

  • Need Sql for this problem

    Hi Gurus
    I have below situtation which need to be sorted out by SQL (10g version)
    Below is the sample data.
    Date     Amt1     Amt2     Amt3     Totl
    201009     10     10     10     30
    201010     20     20     20     90
    201011     30     20     10     150
    Totl is the calculation field and remaining data is available in DB table say tab1. If you see logic of identifying Totl --> addition of Amt1,Amt2,Amt3 with Totl of prev month. For 201010 it is 20+20+20 =60 and this 60 will need to added to 201009 totl 30 and hence final sum is 90.
    Please provide to resolve this.

    You need to do cumulative sum.
    with t
    as
    select 201009 dt, 10 a1, 10 a2, 10 a3 from dual union all
    select 201010, 20, 20, 20 from dual union all
    select 201011, 30, 20, 10 from dual
    select dt, a1, a2, a3, sum(a1+a2+a3) over(order by dt) tot
      from t

  • Need sql for the following requirement

    EMP_DT EMP_TYPE emp_id
    01/01/2011               3 546
    01/03/2011 4 546
    01/05/2011 3 546
    01/08/2011 3 546
    01/09/2011 3 546
    01/10/2011 4 546
    01/12/2011 3 546
    01/14/2011 3 546
    01/16/2011 3 546
    01/18/2011 4 546
    01/19/2011 3 546
    Hi All,
    I have a table with two columns(emp date and type where date is mm/dd/yyyy type tied to employee).
    This data is inserted manually through online application. But behind the scenes I would like keep this date in the following fashion by a delete sql. When run the delete sql it should keep the data in following manner with employe type order 3,4,3,4,3,4 and so on. There shouldn't be any 3 empolyee type rows continuosly. Also when delete the data it should keep the smaller date out of three same employee type dates. example 01/12/2011,01/14/2011,01/16/2011 ---> we will keep the row 01/12/2011 and delete two other dates because they are same type of dates(3).
    EMP_DT EMP_TYPE emp_id
    01/01/2011               3 546
    01/03/2011 4 546
    01/05/2011 3 546
    01/10/2011 4 546
    01/12/2011 3 546
    01/18/2011 4 546
    01/19/2011 3 546

    Hi,
    So, on each row, you need to know what the value of emp_type was on the previous row. That sounds like a job for LAG.
    Here's one way to do that:
    WITH     got_prev_emp_type     AS
         SELECT     emp_dt, emp_type, emp_id
         ,     LAG (emp_type, 1, -1) OVER ( PARTITION BY  emp_id     -- Just guessing
                                                   ORDER BY      emp_dt
                                    ) AS prev_emp_type
         FROM    a_table
    --     WHERE     ...     -- If you need any filtering, put it here
    SELECT       emp_dt, emp_type, emp_id
    FROM       got_prev_emp_type
    WHERE       emp_type     != 3
    OR       prev_emp_type     != 3
    ORDER BY  emp_id
    ,            emp_dt
    ;This assumes that emp_dt is a DATE (or a TIMESTAMP). If it has some other dattype, convert it to a DATE.
    "DELETE" means "permanently remove rows from a table." Is that what you want, or do you just want to exclude some rows from a result set? The query above doesn't actually change the table. If that's what you want to do, you can use the query above as a sub-query in hte WHERE clause of a DELETE statement.
    DELETE  FROM  table_a
    WHERE  (emp_dt, ,emp_type, emp_id)   -- Just guessing
            NOT IN  (
                        WITH   got_prev_emp_type    AS
                    );This assumes that emp_dt, demp_type and demp_id are never NULL.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
    If you're asking about a DML statement, such as DELETE, the sample data will be the contents of the table(s) before the DML, and the results will be state of the changed table(s) when everything is finished.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using. All the code I psoted above assumes you have Oracle 9.1 or higher.

  • Need SQL for this simple logic..

    Hi,
    I have a select statement
    select msi.segment1,micv.CATEGORY_SET_NAME from
    MTL_system_ITEMs msi, MTL_ITEM_CATEGORIES_V micv where msi.INVENTORY_ITEM_ID = micv.INVENTORY_ITEM_ID
    and msi.ORGANIZATION_ID = 853 and msi.ORGANIZATION_ID = micv.ORGANIZATION_ID and
    msi.segment1 = 'C0005'
    which gives me output
    segment1 CATEGORY_SET_NAME
    C0005          Country Of Origin
    C0005          HS COMMODITY
    C0005          Inventory
    C0005          MFG PLANT
    C0005          Order Management Categories
    C0005          Purchasing Categories
    C0005          Sales and Marketing
    I have another select statement
    which gives me output
    segment1 CATEGORY_SET_NAME
    C2601ZE          Inventory
    C2601ZE          Sales and Marketing
    C2601ZE          Purchasing Categories
    C2601ZE          Order Management Categories
    C2601ZE          MFG PLANT
    Where there are 2 rows missing for part C2601ZE from 2nd select
    I want output like below for 2 missed rows which are from 2nd select
    segment1 CATEGORY_SET_NAME
    C2601ZE          Country Of Origin
    C2601ZE          HS COMMODITY
    MINUS is working but its working only for segment1 not for set_name
    Thanks in Advance
    Devender

    select msi.segment1,micv.CATEGORY_SET_NAME
    from MTL_system_ITEMs msi, MTL_ITEM_CATEGORIES_V micv
    where msi.INVENTORY_ITEM_ID = micv.INVENTORY_ITEM_ID
    and msi.ORGANIZATION_ID = 853
    and msi.ORGANIZATION_ID = micv.ORGANIZATION_ID
    and msi.segment1 = 'C2601ZE'
    and micv.CATEGORY_SET_NAME not in (
            select micv.CATEGORY_SET_NAME
            from MTL_system_ITEMs msi, MTL_ITEM_CATEGORIES_V micv
            where msi.INVENTORY_ITEM_ID = micv.INVENTORY_ITEM_ID
            and msi.ORGANIZATION_ID = 853
            and msi.ORGANIZATION_ID = micv.ORGANIZATION_ID
            and msi.segment1 = 'C0005');
    (Not Tested)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Need sql for this logic

    Hi,
    Below is my table with columns like a,b,c
    a      b       c
    1     null   null
    null   2     null
    null  null   3
    I need output like a b c
                              1 2 3

    Hi,
    Here's one way
    SELECT  MIN (a)  AS a
    ,       MIN (b)  AS b
    ,       MIN (c)  AS c
    FROM    my_table;
    I hope this answers your question.
    If not, post  a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
    Point out where the query above is giving the wrong results, and explain, using specific examples, how you get the correct results from the given data in those places.  If you changed the query at all, post your code.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

  • Need answer for below question

    Hi I have data base and two schemas A and B
    A schema have procedure proc1 contain logic to update table emp
    and B schema have emp table.
    Schema A given permision to Schema B for execute proc1 in Schema B
    after execution porc1 in schema B which schema emp table get updates. and why?

    >
    Hi I have data base and two schemas A and B
    A schema have procedure proc1 contain logic to update table emp
    and B schema have emp table.
    Schema A given permision to Schema B for execute proc1 in Schema B
    after execution porc1 in schema B which schema emp table get updates. and why?
    >
    Tell us what answer you gave when you were asked this question. This seems to be either an interview question or a test question from a class.
    Whatever the source of the question your answer should have been that there is not enough information to know for sure what the result will be or why. Missing information that is needed includes
    1. HOW is user B trying to execute the proc in schema A? Directly or within a procedure?
    2. HOW was user B given permission to execute the proc in schema A? Directly or thru a role?
    Grants have to be given directly if B is trying to execute the proc in schema A within a proc of schema B.
    3. HOW was the proc in schema A defined? Using INVOKER rights or DEFINER rights?
    4. Was user B given any privileges to the EMP table in schema A? If so was the privilege granted directly or through a role?
    Without the above information there is no way to know for sure if an exception will be raised or, if no exception is raised, which table will be accessed.

  • Need Code For This Scenerio

    Good Evening,
    i am Srinivas V,
    My actual requirement is that in a JSP Page I had a Link when i click the link in the new page A Text Box to be there if the word pre defined entered the web page content to be viewed else nothing should be displayed .
    Can anyone suggest me regarding this.
    Regards
    Srinivas V

    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <html>
    <head>
    <title>Validator</title>
    <script language="javascript">
         function test(){
              var value=document.getElementById('t').value;
              if(value=="Hello")
                   getFile();
              else
                   document.getElementById('t').focus();     
         function getFile(){
              var req;
              if (window.XMLHttpRequest){
              req = new XMLHttpRequest();
              }else if (window.ActiveXObject) {
              req = new ActiveXObject("Microsoft.XMLHTTP");
         req.onreadystatechange = function(){
         if (req.readyState == 4){     
         if (req.status == 200){
                        document.getElementById('t').style.display='none';
                        document.getElementById('displayDiv').innerText=req.responseText;
    req.open("POST", "http://localhost:8080/heloapp/fileupload.html", true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
         req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.send(null);
    function f()
         document.f1.t1.focus();
    </script>
    </head>
    <body onLoad="f()">
    <form name=f1>
         <input type="text" onblur="test()" name=t1 id='t' />
         <Div id='displayDiv'></Div>
    </form>
    </body>
    </html>
    this is working BUT not executing the .jsp but just opening the file

  • Need query for below requirement

    create table nsk_temp2 (num number,parent_num number,src_num number);
    insert into nsk_temp2 values (1000,null,null);
    insert into nsk_temp2 values (1001,1000,null);
    insert into nsk_temp2 values (1002,1000,null);
    insert into nsk_temp2 values (1010,null,1000);
    insert into nsk_temp2 values (2001,1010,null);
    insert into nsk_temp2 values (2002,1010,null);
    num  parent_num  src_num
    1000          
    1001     1000     
    1002     1000     
    1010          1000
    2001     1010     
    2002     1010     
    Expected output
    num  parent_num  src_num
    1000          
    1001     1000     
    1002     1000     
    1010          1000
    2001     1010     1001
    2002     1010     1002
    2001 -> parent is 1010 and 1010 src_num is 1000 and 1000 is parent for 1001 and 1002, so 1001 and 2001 are identical records

    Hi,
    This does what you requested:
    WITH     got_r_num     AS
         SELECT     num, parent_num, src_num
         ,     ROW_NUMBER () OVER ( PARTITION BY  parent_num
                                   ORDER BY          num
                           )         AS r_num
         FROM    nsk_temp2
    SELECT       d.num, d.parent_num
    ,       NVL ( d.src_num
               , s.num
               )          AS src_num
    FROM           got_r_num  d
    LEFT OUTER JOIN      got_r_num  m  ON  m.num     = d.parent_num
    LEFT OUTER JOIN      got_r_num  s  ON  s.parent_num     = m.src_num
                                   AND s.r_num     = d.r_num
    ORDER BY  d.num
    ;Whether or not it gets the right results for the right reasons, I can't say, since I know so little about the reasons.
    If 1001 and 2001 are identical, aren 1001 and 2002 identical, too? Can the parent_num/num hierarchy extend beyond 2 levels? What would happen if 1000 had more, or fewer, children than 2000?

  • Need SQl for

    I have Table
    create table EXAM
    STUDENT_ID NUMBER,
    MARKS NUMBER
    Data for which looks like
    STUDENT_ID     MARKS
    10     100
    20     300
    30     200
    10     600
    20     400
    30     300
    10     500
    20     700
    30     900
    So if I run this query
    SELECT Student_id,marks ,
    DENSE_RANK() OVER(PARTITION BY Student_id ORDER BY marks ) AS Rank
    FROM exam
    I get this
    STUDENT_ID     MARKS     RANK
    10     100     1
    10     500     2
    10     600     3
    20     300     1
    20     400     2
    20     700     3
    30     200     1
    30     300     2
    30     900     3
    Now My Question is , How I can get the result in (Select statement Note I can write a function or procedure ) to Display Like
    Student ID Mark_rank1 Mark_rank2 Mark_rank3
    10 100 500 600
    20 300 400 700
    30 200 300 900
    Here in Marks I can just upto 3 Ranks
    Thanks In advance

    The following should do it:
    SELECT student_id
    , max(decode(rank, 1, marks, NULL)) mark_rank1
    , max(decode(rank, 2, marks, NULL)) mark_rank2
    , max(decode(rank, 3, marks, NULL)) mark_rank3
    FROM
    (SELECT Student_id,marks ,
    DENSE_RANK() OVER(PARTITION BY Student_id ORDER BY marks ) AS Rank
    FROM exam)
    GROUP BY student_id;
    Note that if you have same marks, it will be only list once. If you want rank1, rank2 to be same if the first 2 marks same, you have to add some other logic there

  • Need help with SQL for Pie Chart

    I am trying to create a pie charge which would have 3 slices.
    Following sql gives me the expected values when I run the sql command:
    select
    round(avg(CATEGORY_1 + CATEGORY_2 + CATEGORY_3 + CATEGORY_4 + CATEGORY_5),0) "OD Engagements",
    round(avg(CATEGORY_6 + CATEGORY_7 + CATEGORY_13),0) "Talent Engagements",
    round(avg(CATEGORY_8 + CATEGORY_9 + CATEGORY_10 + CATEGORY_11 + CATEGORY_12),0) "Other Engagements"
    from OTD_PROJECT
    where STATUS in ('Open','Hold')
    I get 3 columns labeled: OD Engagements, Talent Engagements and Other Engagements with the correct averages based on the the data.
    I have tried several ways to try to get this to work in the SQL for a pie chart, but keep getting the invalid sql message and it won't save. I also tried saving without validation, but no data is shown on the chart at all.
    I want to have a pie, with 3 slices, one labeled OD Engagements with a value of 27, one labeled Talent Engagements with a value of 43 and one labeled Other Engagements with a value of 30. Then I want to be able to click on each pie slice to drill down to a secondary pie chart that shows the breakdown based on the categories included in that type.
    Since I am not grouping based on an existing field I an unsure what the link and label values should be in the chart sql.

    You'll need something like the below. I have no idea what the URL for the drilldown needs to be. It should create an appropriate link in your app for the particular slice. Mainly the code below breaks the SQL results into three rows rather than three columns. It may well have a syntax error since I can't test.
    select linkval  AS LINK,
           title    AS LABEL,
           calc_val AS VALUE
    FROM   (SELECT 'OD Engagements' AS title,
                   round(avg(CATEGORY_1 + CATEGORY_2 + CATEGORY_3 + CATEGORY_4 + CATEGORY_5),0) AS calc_val,
                   'f?p=???:???:' || v('APP_SESSION') || '::NO:?' AS LINKVAL
            from   OTD_PROJECT
            where  STATUS in ('Open','Hold')
            UNION ALL
            SELECT 'Talent Engagements' AS title,
                   round(avg(CATEGORY_6 + CATEGORY_7 + CATEGORY_13),0) AS calc_val,
                   'f?p=???:???:' || v('APP_SESSION') || '::NO:?' AS LINKVAL
            from   OTD_PROJECT
            where  STATUS in ('Open','Hold')
            UNION ALL
            SELECT 'Other Engagements' AS title,
                   round(avg(CATEGORY_8 + CATEGORY_9 + CATEGORY_10 + CATEGORY_11 + CATEGORY_12),0) AS calc_val,
                   'f?p=???:???:' || v('APP_SESSION') || '::NO:?' AS LINKVAL
            from   OTD_PROJECT
            where  STATUS in ('Open','Hold')
           );

  • How to write sql query for below example.

    Hi,
    I have requirement.
    There are number of rows and I need the result through query as follows.Please help me to proved sql query for below mentioned requirement.
    example: table TEST.
    COLA COLB COLC COLD
    MANAGER 5 NULL null
    SR.MANAGE 6 3 NULL
    VP 5 5 4
    I have to write the sql query if COLA IS MANAGER THEN CONSIDER MANGER RECORD,AND IF ANY COLUMN FILED IS NULL FOR MANGER THEN CONSIDER COLA IS SR.MANGER, AND IF ANY COLUMN FILED IS NULL FOR SR,MANGER THEN CONSIDER VP records.
    I need output as below.
    COLB COLC COLD
    5(MANGER) 3(sr.manger) 5(vp)
    Please provide the for above mentioned output.
    Thanks

    <<if COLA IS MANAGER THEN CONSIDER MANGER RECORD>>
    What does this sentence means? COLA does not cnatin a single record but the number of records with diffrent values.
    Regards
    Arun

  • How to write sql query for below mentioned eaxmple.

    Hi,
    I have requirement.
    There are number of rows and I need the result through query as follows.Please help me to proved sql query for below mentioned requirement.
    example: table TEST.
    COLA COLB COLC COLD COLE COLF MANAGER 5 NULL NULL 3 NULL
    SR.MANAGER 6 3 NULL NULL NULL
    VP 5 5 4 5 5
    I have to write the sql query if COLA IS MANAGER THEN CONSIDER MANGER RECORD,AND IF ANY COLUMN FILED IS NULL FOR MANGER THEN CONSIDER COLA IS SR.MANGER, AND IF ANY COLUMN FILED IS NULL FOR SR,MANGER THEN CONSIDER VP records.
    I need output as below.
    COLB COLC COLD COLE COLF
    5(manager) 3(sr.manger) 4(vp) 3(manger) 3(vp)
    Please provide the for above mentioned output.
    Thanks

    Duplicate thread. please view the answer posted in your first thread.
    how to write sql query.
    And, please don't post any duplicate thread.
    Regards.
    Satyaki De.

  • Shell script for below pl/sql script dbms_file_transfer

    Please let me know how tt write the shell script for below pl/sql script dbms_file_transfer it is
    I have trasfer the files from asm into filesystem .
    it is working . but i have to put in the loop
    begin
    dbms_file_transfer.copy_file(
    source_directory_object => 'src',
    source_file_name => 'ncsn',
    destination_directory_object => 'dest',
    destination_file_name => 'ncsn');
    end;
    Edited by: user8680248 on 27/10/2009 20:55

    user8680248 wrote:
    Please let me know how tt write the shell script for below pl/sql script dbms_file_transfer it is
    I have trasfer the files from asm into filesystem .
    it is working . but i have to put in the loop
    begin
    dbms_file_transfer.copy_file(
    source_directory_object => 'src',
    source_file_name => 'ncsn',
    destination_directory_object => 'dest',
    destination_file_name => 'ncsn');
    end;What database version?
    What are you trying to do exactly?
    It's working but you have to put it in a loop. Fine, what's the problem you are having?
    begin
      loop
        exit when ... whatever the exit condition is ...
        dbms_file_transfer.copy_file(
          source_directory_object => 'src',
          source_file_name => 'ncsn',
          destination_directory_object => 'dest',
          destination_file_name => 'ncsn');
      end loop;
    end;

Maybe you are looking for

  • How do you install Drive No. 3?

    2002 quicksilver G4, I have 3 drives and the latest addition (1TB seagate) seems to cause it to freeze up when multitasking or downloading from iTunes. after replacing the logic board and the CPU it appears that this drive has been causing the proble

  • Visa open problem

    Hi            I'm using  labview2009. I've connected 8593E spectrum analyzer using GPIB interface to my PC.The problem is the instrument address is not coming automatically in the VISA open function input when I connect the instrument to my PC. can a

  • Open URLs in Tbird with Firefox

    Using thunderbird-0.5 and firefox-0.8.1, both packages installed with pacman.  When I click on a URL in an email, Thunderbird pops up a dialog asking what application I want to use to open it.  I navigated to /opt/mozilla-firefox/bin/firefox.  Then I

  • Cant restore iPod with updater 3-23-2006

    updater doesnt recognize my iPod or says error and therefore cant restore the iPod (nano)

  • Cannot create Trusted System in NW 7.1 CE

    Hey to all, I've installed NetWeaver Composition Environment 7.1 SP 4. Now I want to set up single sign-on between my Java Stack and an ABAP system. When I try to create a trusted System in NWA after choosing the system (which is provided from SLD on