Select Count and Quantity

Hello
I have made this query =>
SELECT Products.ProductName, COUNT(*)*OrderDetails.Quantity
FROM Products INNER JOIN OrderDetails ON (Products.ProductID=OrderDetails.ProductID)
GROUP BY Products.ProductName, OrderDetails.Quantity, OrderDetails.OrderID
Well it counts the total from each product but it has also Multiplicate it with the quantity.
My quey is not working because it's shows several time the same product name and the quantity is not correct.
The Group by is not working as it should work. And i think i need to use a SUM() for the quantity.
I'm still new to queries.
Any avice?

Looks like this:
DECLARE @products TABLE (productID INT IDENTITY, productName VARCHAR(30))
DECLARE @orderDetails TABLE (orderID INT, productID INT, quantity INT)
INSERT INTO @products (productName) VALUES
('Orange'),('Apple'),('Inflatable Chicken Suit')
INSERT INTO @orderDetails (orderID, productID, quantity) VALUES
(1,1,1),(1,2,1),(2,3,9),(3,2,16)
SELECT SUM(quantity) AS quantity, p.productID, p.productName
FROM @orderDetails o
INNER JOIN @products p
ON o.productID = p.productID
GROUP BY p.productID, p.productName
You where grouping on too many fields. 
Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question.
Also, when posting questions it helps to provide DDL and example data (as I did at the top of my example).

Similar Messages

  • "select count(*)" and "select single *" returns different result

    Good day!
    product version SAP ECC 6.0
    oracle10
    data transfers from external oracle db into customer tables using direct oracle db link
    sometimes I get case with different results from 2 statements
    *mytable has 10 rows
    *1st statement
    data: cnt type I value 0.
    select count( * ) into cnt from mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
    *cnt returns 10 - correct
    *2nd statement
    select single * from  mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
    *sy-dbcnt returns 0
    *sy-subrc returns 4 - incorrect, 10 rows are "invisible"
    but
    1. se16 shows correct row number
    2. I update just one row from "invisible" rows using se16 and 2nd statement returns correct result after that
    can not understand why
    thank you in advance.

    Thank you, Vishal
    but,
    general problem is that
    1. both statements have the same WHERE conditions
    2. 1st return resultset with data (sy-dbcnt=10), 2nd return empty dataset, but must return 1 in sy-dbcnt
    Yes, different meaning, you are right, but must 2nd must return 1, because of "select single *" construction, not 0.
    Dataset to process is the same, WHERE conditions are equal...
    I think the problem is that how ABAP interperets select count(*) and "select single *".
    Maybe "select count (*)" scans only PK from index page(s)? and "select single *" scans data pages? and something is wrong with that?
    I'm new in SAP and didn't find any SAP tool to trace dump of data and indexes pages with Native SQL.
    se16 shows all records.
    And why after simple manual update of just one record using se16 "select single *" returns 1?
    I've just marked one row to update, didn't change any data, then pressed "save".

  • Select Count(*) and actual row are differ: 136 rows vs 65k x 7 rows

    Dear All,
    Good morning. Need your advices. We had a view which is running and producing output to excel files. But recently after one of ours database migration, it were producing differ result: Select Count(*) and actual row are differ: 136 rows vs 65k x 7 rows. Error happen when we export out the row to csv file is produced 65000 rows x 7 worksheep. But when perform select count(*) from RTNEWWIP, result return: 136 rows.
    Is there any way to trace below sql to find where go wrong?
    The Veiw as below:
    CREATE OR REPLACE VIEW RTNEWWIP
    (FAB_ID, PO, PRD_NO, SHP_PRD_NO, LOT,
    WIP_QTY, ROUTEDESC, IN_TIME, STAY_DAY, BACK_DAY,
    WO_FCST_DATE, SHIP_FCST_DATE, SHIP_CONF_DATE, WS_DATE, ROUTERATIO,
    PROCESS, LOTSTATUS, LOTTYPE, RETICLEVERSION, PROCESSVERSION,
    ROUTESEQUENCE, PRIORITY, PROCESSGEN, PROCESSFAMILY)
    AS
    select
    --ord.order_no,
    'SILTERRA' FAB_ID,
    wip.PO_NUMBER PO,
    wip.FW_DEVICE PRD_NO,
    wip.USER_ITEM_DESCRIPTION SHP_PRD_NO,
    wip.LOT_ID LOT,
    wip.CURR_QTY WIP_QTY,
    wip.STEP_DESC ROUTEDESC,
    to_char(wip.RECORD_START_DATE,'DD-MON-YYYY HH24:MI:SS') IN_TIME,
    to_char((sysdate - wip.RECORD_START_DATE),'9999D99') STAY_DAY,
    to_char((wip.SCHEDULED_COMPLETE_DATE - sysdate),'9999D99') BACK_DAY,
    -- (sysdate - wip.RECORD_START_DATE) STAY_DAY,
    -- (wip.SCHEDULED_COMPLETE_DATE - sysdate) BACK_DAY,
    to_char(wip.SCHEDULED_COMPLETE_DATE,'DD-MON-YYYY') WO_FCST_DATE,
    to_char((wip.SCHEDULED_COMPLETE_DATE + 1),'DD-MON-YYYY') SHIP_FCST_DATE,
    --nvl(oel.attribute15, to_char(sysdate+3650,'DD-MON-YYYY')) SHIP_CONF_DATE,
    to_char(nvl(to_date(oel.attribute15,'DD-MON-YYYY'), sysdate+3650),'DD-MON-YYYY') SHIP_CONF_DATE,
    to_char(wip.LOT_START_DATE,'DD-MON-YYYY') WS_DATE,
    --wip.MASK_NO || '/' || wip.MASK_TOTAL ROUTERATIO,
    '''' ||wip.MASK_NO || '/' || wip.MASK_TOTAL ROUTERATIO,
    wip.PLAN_NAME_ACTIVE PROCESS,
    wip.LOT_STATUS LOTSTATUS,
    wip.LOT_TYPE LOTTYPE,
    0 RETICLEVERSION,
    wip.PLAN_VERSION_ACTIVE PROCESSVERSION,
    0 ROUTESEQUENCE,
    wip.PRIORITY PRIORITY,
    ' ' PROCESSGEN,
    ' ' PROCESSFAMILY
    from wip_report wip, lot_fact lf, order_fact orf, order_dim ord,
    apps.oe_order_headers_all@prod_myfabetl oeh,
    apps.oe_order_lines_all@prod_myfabetl oel
    where wip.CUSTNAME like 'Realtek%'
    --AND WIP.FW_DEVICE like '%R25C'
    and wip.ACTIVE_FACT_KEY = lf.RECORD_KEY
    and lf.ORDER_FACT_KEY = orf.RECORD_KEY
    and orf.ORDER_KEY = ord.RECORD_KEY
    and ord.ORDER_NO = to_char(oeh.order_number)
    and oeh.header_id = oel.header_id
    and orf.LINE_ITEM_NUMBER = to_char(oel.line_number)
    and orf.ITEM_SCHEDULE = to_char(oel.shipment_number)
    and wip.LOT_TYPE in ('ENX','PRA','PRD','PRT','CSK','MPW')
    union all
    select --od.order_no,'
    'SILTERRA' FAB_ID,
    od.CUST_PO PO,
    imd.FW_DEVICE_ID PRD_NO,
    nvl(orf.USER_ITEM_DESCRIPTION, nvl(imd.CUST_DEVICE_ID, imd.FW_DEVICE_ID)) SHP_PRD_NO,
    sfl.LOTID LOT,
    sfl.currentcompqty WIP_QTY,
    'CREATED' ROUTEDESC,
    to_char(to_date(substr(recordstartdate,1, 14), 'yyyymmddhh24miss'), 'DD-MON-YYYY HH24:MI:SS') IN_TIME,
    --sysdate - to_date(substr(recordstartdate,1, 14), 'yyyymmddhh24miss') STAY_DAY,
    --to_date(sfl.scheduledcompletedate,'yyyymmdd') - sysdate BACK_DAY,
    to_char(sysdate - to_date(substr(recordstartdate,1, 14), 'yyyymmddhh24miss'),'9999D99') STAY_DAY,
    to_char(to_date(sfl.scheduledcompletedate,'yyyymmdd') - sysdate,'9999D99')BACK_DAY,
    to_char(to_date(sfl.scheduledcompletedate,'yyyymmdd'),'DD-MON-YYYY') WO_FCST_DATE,
    to_char(to_date(sfl.scheduledcompletedate,'yyyymmdd') + 1, 'DD-MON-YYYY') SHIP_FCST_DATE,
    --nvl(oel.attribute15, to_char(sysdate+3650,'DD-MON-YYYY')) SHIP_CONF_DATE,
    to_char(nvl(to_date(oel.attribute15,'DD-MON-YYYY'), sysdate+3650),'DD-MON-YYYY') SHIP_CONF_DATE,
    to_char(to_date(sfl.startdate,'yyyymmdd'), 'DD-MON-YYYY') WS_DATE,
    ' ' ROUTERATIO,
    sfl.tempprocessplan PROCESS,
    sfl.currentstatus LOTSTATUS,
    sfl.currenttype LOTTYPE,
    0 RETICLEVERSION,
    0 PROCESSVERSION,
    0 ROUTESEQUENCE,
    ' ' PRIORITY,
    ' ' PROCESSGEN,
    ' ' PROCESSFAMILY
    from SIL_FW_LOTCREATED_VIEW sfl, order_dim od, order_fact orf, item_master_dim imd,
    apps.oe_order_headers_all@prod_myfabetl oeh,
    apps.oe_order_lines_all@prod_myfabetl oel
    where substr(sfl.salesorderno,1,instr(sfl.salesorderno,'-',1,1)-1)= to_char(od.ORDER_NO)
    and od.RECORD_KEY = orf.ORDER_KEY
    and od.RECORD_CURRENT_FLAG = 1
    and orf.RECORD_CURRENT_FLAG =1
    and to_char(orf.LINE_ITEM_NUMBER) = substr(sfl.salesorderno,instr(sfl.salesorderno, '-',1,1) +1, (instr(sfl.salesorderno, '.',1,1) -1) - instr(sfl.salesorderno, '-',1,1))
    and to_char(orf.ITEM_SCHEDULE) = substr(sfl.salesorderno,instr(sfl.salesorderno, '.',1,1) +1, length(salesorderno) - instr(sfl.salesorderno, '.',1,1))
    and orf.ITEM_MASTER_KEY = imd.RECORD_KEY
    and sfl.customername = 'Realtek'
    and od.ORDER_NO = to_char(oeh.order_number)
    and oeh.header_id = oel.header_id
    and orf.LINE_ITEM_NUMBER = to_char(oel.line_number)
    and orf.ITEM_SCHEDULE = to_char(oel.shipment_number);
    select count(*) from rtnewwip;
    COUNT(*)
    136
    1 row selected

    query might be referring to different environment/schema as you are using database link to access some tables.
    getting result/count from view means executing query which forms that view. try to run that query separately and see the output.
    it may help you to debug

  • Select count(*) and blank element tags

    Is there a way other than column aliases to produce and return an element tag for the following xsql query.
    <xsql:query
    connection="{@cxn}"
    xmlns:xsql="urn:oracle-xsql">
    select count(*) from emp
    </xsql:query>
    Some databases such as SQL Server via a JDBC driver will return a blank column name, thus you'll have an invalid XML document, however SQL Server allows one to use column aliases, such as select count(*) as "count" from emp.
    However some databases such as Progress via a JDBC-ODBC bridge and ODBC driver does NOT allow column aliases. Thus I'll always get the following response:
    <ERROR>oracle.xml.sql.OracleXMLSQLException: String index out of range: </ERROR>
    Question. Can I substitute an element tag when I encounter a blank column name using an action handler? Any ideas? Sample code?
    Steve.

    Please have the data structure as below:
    <datastructure>
    <GROUP name="G_1" source="Q_TEMP">
    <element value="DEPTNO" name="DEPTNO" />
    <element value="DNAME" name="DNAME" />
    <element value="LOC" name="LOC" />
    <GROUP name="G_2" source="Q_TEMP1">
    <element value="ENAME" name="ENAME" />
    <element value="SAL" name="SAL" />
    *</GROUP>*
    *<element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />*
    *<element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>*
    *</GROUP>*
    </datastructure>
    Aggregate functions to be placed at the level you require it. Here you need at G_1, so place it there.

  • Why is the select Count too slow

    I am doing the following select count and calling it from my JSP to get the total number of records... why is it so slow...
    select count(*)
    from
    (select distinct o.receive_id, o.name, o.address
    from order o, item i
    where o.id = i.id
    and o.status = 2 and i.status = 0)

    If the data in the table that you are referring to in the query gets refreshed very often and your high water mark on your table not reset, then this query always runs longer. While deleting data in the table, use 'TRUNCATE' rather than 'DELETE' in your data queries. that would help reset the high water mark and your count() queries will run very very fast.

  • Select count(*) on sql statement returning zero when a matching row exists.

    Our account has an ANSI C application that checks for the existence a row on an Oracle table(s) by using the following SQL:
    int iCount = 0;
    EXEC SQL
    SELECT count(rownum) INTO :iCount
    FROM sys.all_tab_columns
    WHERE table_name IN
    (SELECT table_name FROM
    sys.all_synonyms
    WHERE upper(synonym_name) = upper(:szDestTable))
    AND upper(column_name) = upper(:szColumnName)
    AND owner = 'DBAUSER';
    The bind variables szDestTable and szColumnName are populated with values parsed from columns on another database table. This application is executed through out the day. Occasionally, the application will report a zero in the iCount when there should be a match. I have verified the szDestTable and szColumnName are populated with the correct values which would find a match and they are correct. To make matters even stranger, the application will parse the same input values and find a match (as it should). At some point during the day, and it can be at any time, the application will NOT find a match on the same file, same values. Every subsequent execution of this application will not find a match on the same values. Once the database is brought down and started up in the evening for its normal backups, the application will find a match again on the same values. This problem does not occur every day. I could be a week or a week and a half between incidents.
    I printed the contents of the sqlca.sqqlerrm.sqlerrmc field to a log file. The sqlca.sqlerrm.sqlerrmc field reported an ORA-1405 bind variable was null when the iCount was reporting a zero. When I compiled this application, I set the Proc*C flag to UNSAFE_NULLS=yes since there are other bind variable in the application that can be NULL and that is ok.
    The above SQL is compiled into the C application using the Proc*C compiler. It is compiled using the Oracle 11.2.0.2 libraries. The application is executed against an Oracle 11.2.0.2 database. The database and application are executed on an HP/Unix 11.31 platform.
    This problem did not start occurring until our account went from Oracle 10.2 to Oracle 11.2. Recently, I have changed the SQL to perform a “SELECT COUNT(rownum)” instead of the “SELECT COUNT(*)”. I compiled the application and executed the new application with the SELECT COUNT(rownum) against the same database where the same application with the SELECT COUNT(*) was failing to find a row that actually existed. The application with the SELECT COUNT(rownum) found the matching row as it should have. The new application has been executing in production for about 10 days now without any problems against ten various Oracle 11.2 databases.
    Why would SELECT COUNT(*) and SELECT COUNT(rownum) be any different?

    This forum is about C programming in general, and about using Studio C in particular.
    Your question is about Oracle database programming. You are more likely to find a helpful answer in a forum about database programming. Start here:
    https://forums.oracle.com/forums/category.jspa?categoryID=18

  • How to get count and other field in one select

    Hi,
    I am try to get total rows and some fields in two separate select:
    1. select count(id) into totalRows from mytable m where m.cat = 'CSV'
    2. select m.id, m.cat, m.updateTime from mytable m where m.cat = 'CSV'
    (all rows in mytable are distinct base on id field)
    How can I combine them into one query to make it faster so that no need to compare the m.cat field twice?
    Thanks.
    David

    Here's one solution :
    SQL> desc test;
    Name Null? Type
    ID NUMBER
    CAT VARCHAR2(10)
    UPDATE_TIME TIMESTAMP(6)
    SQL> select * from test;
    ID CAT UPDATE_TIME
    1 XYZ 09-JAN-04 09.04.17.000000 AM
    2 CSV 09-JAN-04 09.04.31.000000 AM
    4 ABCD 09-JAN-04 09.04.41.000000 AM
    5 CSV 09-JAN-04 09.04.53.000000 AM
    6 ABC 09-JAN-04 09.05.00.000000 AM
    7 CSV 09-JAN-04 09.05.06.000000 AM
    8 GGG 09-JAN-04 09.05.17.000000 AM
    7 rows selected.
    SQL> select id, cat, update_time
    2 ,Count(*) Over (Order By cat) As TotCnt
    3 from test
    4 Where cat = 'CSV'
    5 /
    ID CAT UPDATE_TIME TOTCNT
    2 CSV 09-JAN-04 09.04.31.000000 AM 3
    5 CSV 09-JAN-04 09.04.53.000000 AM 3
    7 CSV 09-JAN-04 09.05.06.000000 AM 3
    SQL>
    -- Shailender Mehta -

  • How to reduce logical count and scan count for a select query

    hi,
    I have two tables one is master and other is history. i need to combine this two tables into one temporary table.
    I am using the below query to create temp table.
    Select * into temporders
    from
    (select * from orders
    union
    select * from ordershistory) b
    where updateon= (select max(updateon)from (select updateon,name,units,subunits from orders
    union
    select updateon,name,units,subunits from ordershistory) a
    where updateon <='11/08/2008 11:18 AM' and a.name=b.name and a.units=b.units and a.subunits=b.subunits group by name,units,subunits)
    order by report,subunitsorder
    the statistics for this query:
    SQL Server parse and compile time:
    CPU time = 47 ms, elapsed time = 62 ms.
    Table 'Worktable'. Scan count 556, logical reads 1569, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'ORDERSHISTORY'. Scan count 116, logical reads 339, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'ORDERS'. Scan count 116, logical reads 285, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    SQL Server Execution Times:
    CPU time = 32 ms, elapsed time = 63 ms.
    (115 row(s) affected)
    you see logical reads and scan count for worktable(temporary) is quite high.
    So anyone can give a solution for reduce the scan count and logical reads.
    NOTE: name,units, subunits,updateon columns have primarykey

    SQL ServerAm i reading it properly? :(
    This is Oracle Forum And not the SQL Server.
    Regards.
    Satyaki De.

  • 'select count(*) from x' returns 5460 rows and 'Select * from x' returns 0 rows

    As you can see in the next lines something is wrong in my Oracle (8.0.6 on Win NT 4.0 sp 6a) :
    Oracle8 Enterprise Edition Release 8.0.6.0.0 - Production
    With the Partitioning option
    PL/SQL Release 8.0.6.0.0 - Production
    SQLWKS> SELECT * FROM V_TERRA_TE;
    PERIOD_DATE PERIOD_TIME TERRARCV TERRASND TERCV TESND
    0 rows selected.
    SQLWKS> SELECT COUNT(*) FROM V_TERRA_TE;
    COUNT(*)
    5460
    1 row selected.
    V_TERRA_TE is a complex join of 5 Tables :
    CREATE OR REPLACE VIEW "ACTUATE".V_TERRA_TE AS Select to_date(to_char(p1.period_date,'YYYYMMDD'),'YYYYMMDD') "PERIOD_DATE",
    to_date(to_char(p1.period_time,'HH24:MI'),'HH24:MI') "PERIOD_TIME",
    to_number(p1.caudalrcv + ((p3.caudalrcv + p4.caudalrcv)*(confterrate.conexadslterra/confterrate.conexadsltotal))) "TERRARCV",
    to_number(p1.caudalsnd + ((p3.caudalsnd + p4.caudalsnd)*(confterrate.conexadslterra/confterrate.conexadsltotal))) "TERRASND",
    to_number((p2.caudalrcv * confterrate.pctinfonegocio) + ((p3.caudalrcv + p4.caudalrcv)*(confterrate.conexadslte/confterrate.conexadsltotal)))"TERCV",
    to_number((p2.caudalsnd * confterrate.pctinfonegocio) + ((p3.caudalsnd + p4.caudalsnd)*(confterrate.conexadslte/confterrate.conexadsltotal)))"TESND"
    from p1,p2,p3,p4,confterrate
    where (p1.period_date=p2.period_date)and
    (p1.period_date=p3.period_date)and
    (p1.period_date=p4.period_date)and
    (p1.period_time=p3.period_time)and
    (p1.period_time=p4.period_time)and
    (p1.period_time=p2.period_time)and
    to_char(p1.period_date,'MMYYYY')=to_char(confterrate.period_datetime,'MMYYYY');
    I think that some not reported error happens in the select * with some temporary space or similar but only the message '0 rows selected' is displayed (instead the real error)
    Could somebody help me ?
    Thanks in advance
    Francisco

    Forcing the Join/sort to be made on Disk (not on memory) the problem not happens. This demostrate that ORACLE has a VERY IMPORTANT BUG : It returns 0 rows wich is false.
    To force it to work on disk i use this parameters :
    alter session set sort_area_size=0
    alter session set hash_join_enabled=false
    Note : probably is not the best combination or use of parameters, but using it the query works as espected.

  • How to include Batch Number in Inventory Counting and Print Countsheet

    Hi,
    Could someone let us know how to include the batch number from Inventory Counting and include them in the count sheet when printed?
    Thank you!
    Ramon

    Hi Pam......
    Try this and modify as you want......
    SELECT Distinct T3.[DocDate], T0.[ItemCode], T2.[ItemName], T2.[BatchNum], T0.[Quantity],
    T0.[DocEntry], T0.Price, (T0.Price*T0.[Quantity]) As 'Total'
    FROM PDN1 T0  inner join OIBT T2 on T2.ItemCode=T0.ItemCode and T2.BaseEntry=T0.DocEntry
    INNER JOIN OPDN T3 ON T0.DocEntry = T3.DocEntry
    WHERE T2.[BaseType]=20 and T2.[Direction]=0
    Regards,
    Rahul

  • Value and quantity is not displaying in Tcode MC.9 for some materials

    Dear Sir,
          For the material XYZ Material Type is FERT but when I check the stock in MC.9 with material type FERT, it is not displaying any value and quantity but when I donu2019t put any Material Type it is showing me the value with quantity. Even I tried to change the material type to FERT there also it gave me message as "No data exists for chosen selection". Why this massage is showing like this ?
    Please suggest.
    Regards,
    Sandip Sahu

    Hi,
    Some times there are some issues with S032 info structure. Check report RMCBMBEW and see if you can locate your material,
    Thanks

  • Questions regarding TARGET DATA of a selection set and usage of extracts

    1. In iSetup Users Guide (121azug.pdf), pg5-4, under 'Viewing a Selection Set',
    it has the following lines:
    Supports Update: If the data object updates the target data during load,
    then the Support Update flag appears
    There is no explanation on "target data" in earlier section.
    Can someone explain what this target data is?
    2. In iSetup Users Guide (121azug.pdf), refer to the image on pg5-14, there is a download link
    in order to download extract. What is the downloaded extract for? Is there any documents
    explaining how to use the downloaded extracts? I am thinking that this downloaded extract
    can be used to upload in other env but I am not sure how to use these.
    Any advise?
    Thanks.

    You are on the right track!
    +--the entire iTunes folder found in My Music+
    This contains the itunes library database files (iTunes Library.itl which has metadata on ratings, play counts) and all the itunes library content files (Artist/Album, movies, etc.)
    The lyrics are inside each songs' file.
    The Artwork should also be in this folder.
    +-User Name\Application Data\Apple Computer+
    +-User Name\Local Settings\Apple Computer+
    These include the backups you need for the ipod and apps data.
    You don't need to deauthorize if you are simply reinstalling itunes. You only need to deauthorize if you are reinstalling Windows itself.
    +--Can I copy the iTunes folder from the external HDD and paste it back into the same location after I recover my laptop+
    Yes
    +if the version of iTunes is slightly different (I have 10.1.0.54)?+
    If the new version is at least 10.1.0.54
    It won't work to go backwards to an older version such as v9.0

  • Performance issue when using select count on large tables

    Hello Experts,
    I have a requirement where i need to get count of data  from a database table.Later on i need to display the count in ALV format.
    As per my requirement, I have to use this select count inside a nested loops.
    Below is the count snippet:
    LOOP at systems assigning <fs_sc_systems>.
    LOOP at date assigning <fs_sc_date>.
    SELECT COUNT( DISTINCT crmd_orderadm_i~header )
       FROM crmd_orderadm_i
       INNER JOIN bbp_pdigp
           ON crmd_orderadm_iclient EQ bbp_pdigpclient               "MANDT is referred as client
         AND crmd_orderadm_iguid  EQ bbp_pdigpguid
         INTO w_sc_count
    WHERE crmd_orderadm_i~created_at BETWEEN <fs_sc_date>-start_timestamp
         AND <fs_sc_date>-end_timestamp
         AND bbp_pdigp~zz_scsys   EQ <fs_sc_systems>-sys_name.
    endloop.
    endloop.
    In the above code snippet,
    <fs_sc_systems>-sys_name is having the system name,
    <fs_sc_date>-start_timestamp is having the start date of month
    and <fs_sc_date>-end_timestamp is the end date of month.
    Also the data in tables crmd_orderadm_i and bbp_pdigp is very large and it increases every day.
    Now,the above select query is taking a lot of time to give the count due to which i am facing performance issues.
    Can any one pls help me out to optimize this code.
    Thanks,
    Suman

    Hi Choudhary Suman ,
    Try this:
    SELECT crmd_orderadm_i~header
      INTO it_header                 " interna table
      FROM crmd_orderadm_i
    INNER JOIN bbp_pdigp
        ON crmd_orderadm_iclient EQ bbp_pdigpclient
       AND crmd_orderadm_iguid   EQ bbp_pdigpguid
       FOR ALL ENTRIES IN date
    WHERE crmd_orderadm_i~created_at BETWEEN date-start_timestamp
                                          AND date-end_timestamp
       AND bbp_pdigp~zz_scsys EQ date-sys_name.
        SORT it_header BY header.
        DELETE ADJACENT DUPLICATES FROM it_header
        COMPARING header.
        describe table it_header lines v_lines.
    Hope this information is help to you.
    Regards,
    José

  • How to count and display the number of records in a database table

    My webpage has a list of items and their details, every item has a button
    Read / Make comments that loads the item in its own page displaying
    a comments form and previous comments.
    This is all working fine.
    I would like to add to each item information stating how many comments have
    been made about that item.
    Allowing the user to see before hand if it is worth while clicking on the
    Read / Make comments button.
    Ideally each item will have a different number of comments.
    The problem I have is outputing the number of comments associated with each item.
    My comments table is called guest my items table is called titles.
    I'm sure mysql statement is correct -
    The table guest currently has 7 comments,
    Item 1 has 3 comments
    Item 2 has 2 comments
    Item 3 has 1 comment
    Item 4 has 1 comment
    When I test the query in dreamweaver
    $Recordset1 = "SELECT COUNT(guest.software_id) as COUNT, titles.id FROM titles LEFT JOIN guest ON titles.id = guest.software_id GROUP BY guest.software_id";
    the outoput is a list showing 2, 3, 1, 1
    My problem is, getting the totals into my repeat region.
    I tried the following line
    <td align="left" valign="top" bgcolor="#e5f8cb">Current comments:<?php echo $row_Recordset1['COUNT']; ?></td>
    resulting in all comments so far displaying 0
    I have highlighted in bold the parts that I am having difficulty with.
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
      if (PHP_VERSION < 6) {
        $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
      $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;   
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
          break;
        case "date":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
      return $theValue;
    $colname_rsTitles = "-1";
    if (isset($_GET['id'])) {
      $colname_rsTitles = $_GET['id'];
    mysql_select_db($database_abe, $abe);
    $query_rsTitles = sprintf("SELECT title, company, `description`, resources, location, url, image, keyword, copies FROM titles WHERE id = %s ORDER BY id ASC", GetSQLValueString($colname_rsTitles, "int"));
    $rsTitles = mysql_query($query_rsTitles, $abe) or die(mysql_error());
    $row_rsTitles = mysql_fetch_assoc($rsTitles);
    $totalRows_rsTitles = "-1";
    if (isset($_GET['id'])) {
      $totalRows_rsTitles = $_GET['id'];
    $colname_rsTitles = "-1";
    mysql_select_db($database_abe, $abe);
    $query_rsTitles = sprintf("SELECT title, company, `description`, resources, location, url, image, keyword, copies FROM titles WHERE id = %s ORDER BY id ASC", GetSQLValueString($colname_rsTitles, "int"));
    $rsTitles = mysql_query($query_rsTitles, $abe) or die(mysql_error());
    $row_rsTitles = mysql_fetch_assoc($rsTitles);
    $totalRows_rsTitles = mysql_num_rows($rsTitles);
    mysql_select_db($database_abe, $abe);
    $query_rs_comments = "SELECT * FROM guest";
    $rs_comments = mysql_query($query_rs_comments, $abe) or die(mysql_error());
    $row_rs_comments = mysql_fetch_assoc($rs_comments);
    $totalRows_rs_comments = mysql_num_rows($rs_comments);
    mysql_select_db($database_abe, $abe);
    $query_rs_users = "SELECT * FROM users";
    $rs_users = mysql_query($query_rs_users, $abe) or die(mysql_error());
    $row_rs_users = mysql_fetch_assoc($rs_users);
    $totalRows_rs_users = mysql_num_rows($rs_users);
    mysql_select_db($database_abe, $abe);
    $query_Recordset1 = "SELECT COUNT(guest.software_id) as COUNT, titles.id FROM titles LEFT JOIN guest ON titles.id = guest.software_id GROUP BY guest.software_id";
    $Recordset1 = mysql_query($query_Recordset1, $abe) or die(mysql_error());
    $row_Recordset1 = mysql_fetch_assoc($Recordset1);
    $totalRows_Recordset1 = mysql_num_rows($Recordset1);
    mysql_select_db($database_abe, $abe);
    if(!isset($_POST['softwareLevel'])){
    if (!isset($_GET['class_id'])) {
    //show all software titles
    $query_rsTitles = "SELECT id, title, company, `description`, resources, location, url, image, keyword, copies FROM titles ORDER BY id ASC";
    }else{
    //show software titles filtered by Literacy of Numeracy (using URL GET variable)
    $query_rsTitles = "SELECT id, title, company, `description`, resources, location, url, image, keyword, copies FROM titles WHERE titles.class_id = ". GetSQLValueString($_GET['class_id'], "int") ." ORDER BY id ASC";
    }else{
    //show software titles filtered by Level (using Form POST variable)
    $query_rsTitles = "SELECT id, title, company, `description`, resources, location, url, image, keyword, copies FROM titles WHERE titles.level_id = ". GetSQLValueString($_POST['softwareLevel'], "int") ." ORDER BY id ASC";
    $rsTitles = mysql_query($query_rsTitles, $abe) or die(mysql_error());
    $row_rsTitles = mysql_fetch_assoc($rsTitles);
    $totalRows_rsTitles = mysql_num_rows($rsTitles);
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <?php $pagetitle="ABE Software Locator"?>
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><?php echo $pagetitle ?></title>
    <link rel="stylesheet" href="../../includes/styles.css" type="text/css" media="screen" />
    <style type="text/css">
    body {
    background-color: #FFF;
    </style>
    </head>
    <body>
    <?php include("../../includes/header.php"); ?>
        <div><table width="70%" border="0" align="center" cellpadding="3" cellspacing="0">
      <tr>
        <td width="29%" height="50" align="center"><a href="software_detail.php">Back to Locator</a></td>
        <td width="50%" align="center"><a href="../../index.php">Welcome Page</a></td>
        <td width="21%" align="center"><a href="../../logout.php">Log Out</a></td>
      </tr>
      <tr>
        <td colspan="3" align="center"><strong> There Are <span class="totalrecordsnumber"><?php echo $totalRows_rsTitles ?></span>  Software Titles Listed</strong></td>
      </tr>
      <tr>
        <td> </td>
        <td> </td>
        <td> </td>
      </tr>
    </table>
        <?php do { ?>
          <table width="820" border="0" align="center" cellpadding="3" cellspacing="2">
            <tr>
              <td width="206" height="200" rowspan="3" align="center" bgcolor="#FFFFFF"><img src="images/<?php echo $row_rsTitles['image']; ?>" alt="<?php echo $row_rsTitles['title']; ?>" /></td>
              <td colspan="3" align="center" bgcolor="#086b50"><h2><?php echo $row_rsTitles['title']; ?></h2></td>
            </tr>
            <tr>
              <td colspan="3" align="center" bgcolor="#f6b824"><strong>Made by:</strong> <?php echo $row_rsTitles['company']; ?></td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top" bgcolor="#e5f8cb"><p class="ptaglineheight"><strong>Description: </strong><?php echo $row_rsTitles['description']; ?></p></td>
            </tr>
            <tr>
              <td colspan="2" align="left" valign="top" bgcolor="#e5f8cb"><span class="tabletext"><strong>Keywords</strong></span><strong>: </strong><?php echo $row_rsTitles['keyword']; ?></td>
              <td colspan="2" align="left" valign="top" bgcolor="#e5f8cb"><strong>Resources:</strong> <?php echo $row_rsTitles['resources']; ?></td>
            </tr>
            <tr>
              <td colspan="4" align="left" valign="top" bgcolor="#e5f8cb"><strong>Web Address:</strong> <a href="<?php echo $row_rsTitles['url']; ?>" target="_blank"><?php echo $row_rsTitles['url']; ?></a></td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top" bgcolor="#e5f8cb"><strong>Is installed on:</strong> <?php echo $row_rsTitles['location']; ?></td>
              <td width="195" align="left" valign="top" bgcolor="#e5f8cb"><strong>Copies available:</strong><?php echo $row_rsTitles['copies']; ?></td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top" bgcolor="#e5f8cb"><a href="fulltitle.php?software_id=<?php echo $row_rsTitles['id']; ?>&amp;id=<?php echo $row_rsTitles['id']; ?>">Read / Make Comments About This Software</a></td>
              <td align="left" valign="top" bgcolor="#e5f8cb">Current comments:<?php echo $row_Recordset1['COUNT']; ?></td>
            </tr>
          </table> 
          <br />
          <?php } while ($row_rsTitles = mysql_fetch_assoc($rsTitles)); ?>
        </div>
        <?php include("../../includes/footer.php"); ?>
    </body>
    </html>
    <?php
    mysql_free_result($rsTitles);
    mysql_free_result($rs_comments);
    mysql_free_result($rs_users);
    mysql_free_result($Recordset1);

    I changed the mysql as you suggested GROUP BY titles.id
    and added a while loop to iterate over the data
    mysql_select_db($database_abe, $abe);
    $query_Recordset1 = "SELECT COUNT(guest.software_id) as COUNT, titles.id FROM titles LEFT JOIN guest ON titles.id = guest.software_id GROUP BY titles.id";
    $Recordset1 = mysql_query($query_Recordset1, $abe) or die(mysql_error());
    $row_Recordset1 = mysql_fetch_assoc($Recordset1);
    $totalRows_Recordset1 = mysql_num_rows($Recordset1);
    $row_Recordset1 = mysql_query($query_Recordset1) or die(mysql_error());
    <td>Current comments:<?php
    if($row_Recordset1)
    while($row = mysql_fetch_array($row_Recordset1))
    echo $row['COUNT'];
    } ?></td>
    The first item now displays the following,
    comments:2311000000000000000000000000000
    all others
    comments:
    the number matched the database table exactly, 30 records 4 of which have 2, 3, 1, 1 comments.
    It looks as if the problem is trying to get the repeat region to pick up on it!

  • Runtime error in Dynamic internal table with AMOUNT and Quantity Fields..

    Dear friends,
    I am attempting write a dymanic Select Statement (with joins).
    And the sleect query looks like this..
      SELECT (LT_SEL_LIST)
      INTO CORRESPONDING FIELDS OF
      TABLE <DYN_TABLE>
      FROM (LT_FROM_LIST)
      WHERE (LT_WHERE3).
    Here the into table is a dynamically created internal table..
    which is created by ...this
    CALL METHOD CL_ALV_TABLE_CREATE=>CREATE_DYNAMIC_TABLE
        EXPORTING
          IT_FIELDCATALOG = IT_OUTPUT2[]
        IMPORTING
          EP_TABLE        = DY_TABLE.
    the it_output2 contains the the fieldcatlog information of dynamically given fields :-
    like:-
           TABNAME
           FIELDNAME
           DATATYPE
           LENG
           INTTYPE
           ROLLNAME
           DECIMALS
           REFTABLE
           REFFIELD
    i mean the internal table is constructed with reference to all the bove metadata.
    Problem:- This query run fine with all the fields Except AMOUNT AND QUANTITY fields....
    When the selection list contain VBAK-NETWR or MSEG-MENGE..It throws a runtime error.
    "The data read during a SLECT access couldnt be inserted into the target field,either conversion is not supported for
    the target field's type or the target field is too short."
    after this I even tried to construct the dynamic table with CFILEDNAME and QFIELDNAME in the Fieldcatalog.
    so now my fieldcatlog looks like this:---
    LOOP AT IT_DD03L..
      IF IT_DD03L-DATATYPE = 'CURR'.
           TABLEFIELD-CFIELDNAME = IT_DD03L-FIELDNAME .
           ENDIF.
       IF IT_FIELDCAT3-DATATYPE = 'QUAN'.
           TABLEFIELD-QFIELDNAME = IT_DD03L-FIELDNAME .
      ENDIF.
           TABLEFIELD-TABNAME     = IT_DD03L-TABNAME.
           TABLEFIELD-FIELDNAME   = IT_DD03L-FIELDNAME.
           TABLEFIELD-DATATYPE    = IT_DD03L-DATATYPE.
           TABLEFIELD-INTLEN      = IT_DD03L-LENG.
           TABLEFIELD-INTTYPE     = IT_DD03L-INTTYPE .
           TABLEFIELD-ROLLNAME    = IT_DD03L-ROLLNAME.
           TABLEFIELD-DECIMALS    = IT_DD03L-DECIMALS.
           TABLEFIELD-REF_TABLE   = IT_DD03L-REFTABLE.
           TABLEFIELD-REF_FIELD   = IT_DD03L-REFFIELD.
    APPEND TABLEFIELD.
    CLEAR TABLEFIELD.
    ENDLOOP.
    Note:- this is a test code so ignore performance issues...
    Please help me with some code ...to avoid the Runtime erorr.
    Thanks,
    jeevan.

    Hi Jeevan,
    Why are moving only few fields from DD03L table to your field catalog? Why don't you use move-corresponding? The following code works for me in ECC6.0.
    data: it_dd03l type table of dd03l initial size 0,
          ls_dd03l type dd03l,
          lt_fldcat TYPE lvc_t_fcat,
          ls_fldcat TYPE lvc_s_fcat,
          ls_where(72) TYPE c,
          lt_where LIKE TABLE OF ls_where,
          lt_fld LIKE TABLE OF ls_where,
          lt_data_dy TYPE REF TO data.
    field-symbols: <ft_data> TYPE STANDARD TABLE.
    select * into table it_dd03l from dd03l
        where tabname = 'VBAK'
          and ( fieldname = 'VBELN' or fieldname = 'NETWR' ).
    check sy-subrc eq 0.
    loop at it_dd03l into ls_dd03l.
      move-corresponding ls_dd03l to ls_fldcat.
      append ls_fldcat to lt_fldcat.
      move ls_dd03l-fieldname to ls_where.
      append ls_where to lt_fld.
      if ls_dd03l-fieldname = 'VBELN'.
        clear ls_where.
        concatenate ls_dd03l-fieldname ' <> ''''' into ls_where.
        append ls_where to lt_where.
      endif.
    endloop.
    check not lt_fldcat is initial.
    CALL METHOD cl_alv_table_create=>create_dynamic_table
          EXPORTING
            it_fieldcatalog           = lt_fldcat
          IMPORTING
            ep_table                  = lt_data_dy
          EXCEPTIONS
            generate_subpool_dir_full = 1
            OTHERS                    = 2.
        IF sy-subrc <> 0.
          RAISE no_configuration_data.
        ENDIF.
        ASSIGN lt_data_dy->*  TO <ft_data>.
    check sy-subrc eq 0.
    select (lt_fld) from VBAK into corresponding fields of table
        <ft_data>
        where (lt_where).
    Thanks
    Bala

Maybe you are looking for

  • How can I execute a Procedure with OUT variable is %ROWTYPE on SQL Prompt

    Hi, I have a procedure with OUT variable is %ROWTYPE How can I execute the following procedure on SQL prompt. (without creating anonymous block) CREATE OR REPLACE PROCEDURE zz_sp_EMP(VEMPNO IN EMP.EMPNO%TYPE, V_REC IN OUT EMP%ROWTYPE) AS BEGIN SELECT

  • Autoboxing and == operator

    Hi, I have a problem with the following code : public class Equivalence {      public static void main(String args[]) {           Integer n1 = new Integer(47);           Integer n2 = new Integer(47);           System.out.println(n1 == n2);           

  • No APEX product option on MetaLink Create SR page

    Am I missing something or is there really no option in MetaLink to create an SR for an ApEx issue? Gregory.

  • What is a good Homesite query builder alternative?

    Hello again. I'm making the switch from Homesite to DW. We are using Sybase, and have no access to an enterprise manager console or anything like that for making direct SQL queries. So we used Homesite's built in query builder rather than write CF co

  • Please  help me. I m a beginner in Sql.

    Hi, My database contains below informations. scrip_code scrip_name client_code qty b_s 500100 TISCO 47198      1000 BUY 500100 TISCO 47198 1000 SELL 500101 RELCAPITAL 47198 1000 BUY 500101 RELCAPITAL 47198 1000 SELL 500102 RELIANCE 47198 1000 BUY 500