Outputing Total Numbers of Rows Returned in query using a CTE

The query below is not being parsed by SQL Server and I can understand that the column name needs to be aliased which I have equally done. The idea behind the query is to output the count of rows using a CTE.
USE AdventureWorks2012
DECLARE @TotalRows INT = 0 -- OUTPUT
WITH Invoice AS (
SELECT @TotalRows = COUNT(CustomerID)
, SalesOrderID
, CustomerID
, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate = '2007/07/01'
GROUP BY SalesOrderID
, CustomerID
, OrderDate
SELECT c.CustomerID
, Invoice.SalesOrderID
, Invoice.OrderDate
FROM Sales.Customer AS c
INNER JOIN Invoice
ON c.CustomerID = Invoice.CustomerID
ORDER BY Invoice.OrderDate DESC;
How do I modify the query to produce the desired retult?
Thank you.
Zionlite

Zionlite,
check this>?
DECLARE @TotalRows INT = 0 -- OUTPUT
;WITH Invoice AS
SELECT COUNT(CustomerID) over()
as customer_count
, SalesOrderID
, CustomerID
, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate = '2001/07/01'
GROUP BY SalesOrderID
, CustomerID
, OrderDate
SELECT c.CustomerID
, Invoice.SalesOrderID
, Invoice.OrderDate
, customer_count
FROM Invoice
LEFT JOIN Sales.Customer AS c
ON c.CustomerID = Invoice.CustomerID
ORDER BY Invoice.OrderDate DESC;
So the above query, gives you the rows_count as a seprate column itself. Now you may use this to update the variable by pushing the results to  a temp table and selecting the column value.
Method 2:
Another method can be using the rowcount method..
DECLARE @TotalRows INT = 0 -- OUTPUT
;WITH Invoice AS
SELECT SalesOrderID
, CustomerID
, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate = '2001/07/01'
GROUP BY SalesOrderID
, CustomerID
, OrderDate
SELECT c.CustomerID
, Invoice.SalesOrderID
, Invoice.OrderDate
FROM Invoice
LEFT JOIN Sales.Customer AS c
ON c.CustomerID = Invoice.CustomerID
ORDER BY Invoice.OrderDate DESC;
select @totalrows=@@rowcount
select @TotalRows
Thanks,
Jay
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

Similar Messages

  • How to get total number of rows return by query

    hi all
    i am using forms 6i with oracle 10G in windows environment....
    i have a tabular form now i want to know that how many rows return by the query...like when user click on enter query and then give any search criteria and then execute query..it displays the records but i want to count the records that how many rows are return.............
    hope you understant what i mean
    Thanks in advance
    Regards

    U can use
    "Select count(*) from <table> where <condition>"
    <condition> is the where clause being used during "Execute Query"
    this will give u the no of records in query.
    And second option is to take a summary column. whose function is set "COUNT" and
    "Summarized item" should contain a column that will never be blank. After execute query this column will give u no of records in block.
    Regards....

  • Numbering the row returned

    Hi,
    i m having difficulties numbering the rows returned..
    im using rownum function, but it returns me duplicate records even after i distinct it.
    and also it doesnt start from 0
    ANy other way to number the row ?
    EDIT: using oracle function : ROW_NUMBER() also give me the same issue
    Edited by: Sosys on Dec 17, 2008 11:50 AM

    THE query is big..
    it's difficult to post and impossible to test by you..
    just assume this :
    NAME PHONE LOCATIOn
    JOHN 111 NY
    JOHN 111 NY
    MARK 112 NJ
    MARK 112 NJ
    CAT 113 WA
    and i want to put number from 1,2,3,4,5 in front..
    NO NAME PHONE LOCATIOn
    1 JOHN 111 NY
    2 JOHN 111 NY
    3 MARK 112 NJ
    4 MARK 112 NJ
    5 CAT 113 WA
    How u do this ?
    i used this :rank() over( order by NAME desc) NO,
    and it will give me:
    NO NAME PHONE LOCATIOn
    1 JOHN 111 NY
    1 JOHN 111 NY
    2 MARK 112 NJ
    2 MARK 112 NJ
    3 CAT 113 WA
    How to make it number from 1 to 5 ?
    Thans.

  • How do you limit the number of rows return from query?

    How do you limit the number of rows return from query? Do all databases support this kind of feature?

    i think the standard is limit
    to get the top 30
    select * from mytable LIMIT 30;returns the first 30 rows
    also if you want a range
    select * from mytable LIMIT 10,30;returns 30 rows starting from 10
    this last one is useful for displaying ranges... something similar happens in these forums when viewing topics and messages

  • How to get the total numbers of pages have been printed using pl/sql

    Dear All ,
    I want to store the total number of physical pages printed into a database table,, how could I retrieve the value of the total number of pages .
    I am using Oracle Report 6i
    thnxxx in advance :)

    At the end of your report (i.e. after all the frames from your data model) place a dummy field. You can get the page number with srw.get_page_num in the format trigger of this field. Since this is the last field of your report, this is also the last page number.

  • Output the number of rows returned in a query

    How do I find out the number of rows that are returned in a query?
    COUNT function I guess can only be used when there is only one table involved. How do I do it for multi table query like JOIN?
    For example
    SELECT emp.first_name, emp.last_name, jobs.age FROM employees emp, jobs
    WHERE emp.employee_id=jobs.employee_id

    Hi,
    You can get the num of rows info
    select count(*) from (SELECT emp.first_name, emp.last_name, jobs.age FROM employees emp, jobs
    WHERE emp.employee_id=jobs.employee_id) ;
    regards
    Jafar
    http://www.oracledbarea.blogspot.com

  • Not getting total of results row in bex query

    Hi Experts,
    In Bex I have created new formula variable which is the Percentage of On time delivery for a particular vendor. The problem is when I use calendar year and vendor in rows and CK in columns and execute the query, I am not getting the the total value of particular vendor percentage for the year. Instead I am getting the value of 'X'.
    I tried to change the calculation result as "summation" but still I am facing the same issue.. If need more explanation i can give screenshots.
    Please help.
    Regards,
    Mathivanan

    Hi Anshu,
    Thanks for your valuable reply. Here is the screenshots
    The formula variable I have created is based on some CK's.  When i run query for all vendors I am getting the result percentage. But when I run the query with calendar year I am getting result as below
    The OTD Percentage is not the total % of the year 2010 for the particular supplier(vendor).

  • Wish to find out number of rows returned from query

    hi,
    is it possible to determine how many rows have been returned after a query has been executed?
    thank you.

    It doesn't seem like there is a method to do it for you, [...]There can't be such a method that's guaranteed to work for all databases. Many databases just hand you a cursor with the query results, and you have to walk the cursor to find the complete set. It's even possible for the DB to continue computing the query in the background and just give you a cursor to walk and consume what it has already generated.
    So no, you have to walk the result set (effectively pulling everything over to the client) to count the number of rows..

  • Pick the last row returned from query

    hii...
    i have a query thats returns...
    SQL> WITH tbl_zone AS (
      2       SELECT to_date('02/03/2010', 'DD/MM/YYYY') close_date FROM dual UNION ALL
      3       SELECT to_date('03/03/2010', 'DD/MM/YYYY') FROM dual UNION ALL
      4       SELECT to_date('04/03/2010', 'DD/MM/YYYY') FROM dual UNION ALL
      5       SELECT to_date('09/03/2010', 'DD/MM/YYYY') FROM dual UNION ALL
      6       SELECT to_date('11/03/2010', 'DD/MM/YYYY') FROM dual)
      7    SELECT  TRUNC(close_date, 'IW') close_date
      8   from tbl_zone t
      9   ORDER BY 1 DESC;
    CLOSE_DATE
    08/03/2010
    08/03/2010
    01/03/2010
    01/03/2010
    01/03/2010i want the query to return just i row and that should be the greatest date
    in the above example
    the query should return single row out of the 2 greatest dates, 08/03/2010.
    CLOSE_DATE
    08/03/2010Please any one suggest...

    How about row_number()
    SQL> with tbl_zone as (
      2       select to_date('02/03/2010', 'dd/mm/yyyy') close_date from dual union all
      3       select to_date('03/03/2010', 'dd/mm/yyyy') from dual union all
      4       select to_date('04/03/2010', 'dd/mm/yyyy') from dual union all
      5       select to_date('09/03/2010', 'dd/mm/yyyy') from dual union all
      6       select to_date('11/03/2010', 'dd/mm/yyyy') from dual
      7       )
      8  --
      9  --
    10  --
    11  select close_date
    12  from ( select trunc(close_date, 'iw') close_date
    13         ,      row_number() over ( order by close_date desc)  rn
    14         from   tbl_zone t
    15       )      
    16  where rn=1;
    CLOSE_DATE
    08-03-2010 00:00:00

  • How to Output Totals to one Row?

    Post Author: robertr
    CA Forum: General
    Hi - I have a giant report that contains basic info such as name, employee id, check date, check hours and check earnings.  The problem is that I need only the totals for each employee and not the entire check earnings for each date.  Can someone please advise on how I can create a report with the output I would like.  Here is a sample of the data that I would like to summarize:
    Pay Grp
    EMPID
    Name
    Title
    F/P
    Status
    Chk Date
    ERNCD
    EARNINGS
    HOURS
    YOU
    123456
    Doe, John
    Accounting Assistant
    F
    A
    2/29/2008
    HOL
    131.84
    8.00
    YOU
    123456
    Doe, John
    Accounting Assistant
    F
    A
    2/29/2008
    SIK
    329.60
    20.00
    YOU
    123456
    Doe, John
    Accounting Assistant
    F
    A
    2/29/2008
    972.32
    59.00
    YOU
    4235
    Young, Neil
    Booker
    F
    A
    2/29/2008
    5,008.33
    87.00
    YOU
    99999
    Allen,Daniel J
    Director
    F
    A
    2/29/2008
    3,750.00
    87.00
    YOU
    88888
    Allen,Jeanine
    Manager
    F
    A
    2/29/2008
    2,500.00
    87.00
    WYL
    565656
    Allen,Larita
    Sales and Service Representati
    F
    A
    2/29/2008
    RTA
    400.00
    40.00
    WYL
    565656
    Allen,Larita
    Sales and Service Representati
    F
    A
    2/29/2008
    870.00
    87.00
    PREFERRED OUTPUT - SUMMARIZED - YOU CAN SEE THAT THE HOURS AND EARNINGS HAVE BEEN TOTALED
    Pay Grp
    EMPID
    Name
    Title
    F/P
    Status
    EARNINGS
    HOURS
    YOU
    123456
    Doe, John
    Accounting Assistant
    F
    A
    1,433.76
    87.00
    YOU
    4235
    Young, Neil
    Booker
    F
    A
    5,008.33
    87.00
    YOU
    99999
    Allen,Daniel J
    Director
    F
    A
    3,750.00
    87.00
    YOU
    88888
    Allen,Jeanine
    Manager
    F
    A
    2,500.00
    87.00
    WYL
    565656
    Allen,Larita
    Sales and Service Representati
    F
    A
    1,270.00
    127.00

    Post Author: SKodidine
    CA Forum: General
    Easy enough at first glance.  I am assuming that each employee can only belong to one pay group.
    Group on EmpID
    Suppress Group Header and Detail Section
    Place the fields Pay Group, EmpID, Name, Title, F/P and Status on the group footer
    Create a running total for the field Earnings and choose SUM for type of summary, Evaluate for each record and RESET on change of group and choose the EmpID group you created in step 1.
    Repeat step 4 but this time choose the field HOURS.
    Place both running totals in the group footer.
    The report should now show only summary totals.  This is the simplest scenario.  If one employee can belong to more than one pay group or status etc, then you will have to group by those fields and perform steps 3 u2013 6 on the innermost grouping.

  • Too many rows return on query?

    I am trying to write a query to pull data from two different tables. There are 444 records in p table and 650 records in the T table yet when i run my query I am getting over 10,000+ records??? When I look at the results it seems that it is applying multiple dates per person when there is only 1 end date? and showing multiple languageid's when only 1 language is spoken?
    SELECT DISTINCT P.LASTNAME, P.FIRSTNAME, T.LANGUAGEID, T.TEST_TYPE, T.END_DATE, T.SCORE1, T.SCORE2
    FROM PS_TEST_SCORES T, PS_PERSONNEL P
    WHERE T.SCORE1 >='2'
    AND T.SCORE2 >='2'
    AND T.END_DATE between to_date( '01-jan-2009 00:00:00', 'dd-mon-yyyy hh24:mi:ss' )
    and to_date( '28-jan-2011 00:00:00', 'dd-mon-yyyy hh24:mi:ss' )
    ORDER BY P.LASTNAME;
    example result would be
    jones john german test_type 24-dec-09
    jones john german 22-jan-09
    jones john german 01-feb-10
    jones john spanish 05-aug-10

    user11384952 wrote:
    sorry .. I missed the join.. pardon that I am a newbie
    I changed it to ....
    SELECT DISTINCT P.SSN,P.LASTNAME, P.FIRSTNAME, T.LANGUAGEID, T.TEST_TYPE, T.END_DATE, T.SCORE1, T.SCORE2
    FROM PS_TEST_SCORES T, PS_PERSONNEL P
    WHERE SELECT DISTINCT P.LASTNAME, P.FIRSTNAME, T.LANGUAGEID, T.TEST_TYPE, T.END_DATE, T.SCORE1, T.SCORE2
    FROM PS_TEST_SCORES T, PS_PERSONNEL P
    WHERE PS_TEST_SCORE.SSN=PS_PERSONNEL.SSN
    AND T.SCORE1 >='2'
    AND T.SCORE2 >='2'
    AND T.END_DATE between to_date( '01-jan-2009 00:00:00', 'dd-mon-yyyy hh24:mi:ss' )
    and to_date( '28-jan-2011 00:00:00', 'dd-mon-yyyy hh24:mi:ss' )
    ORDER BY P.LASTNAME;That can't be right: it has 2 SELECT clauses, 2 FROM clauses and 2 WHERE clauses.
    Perhaps you meant
    SELECT DISTINCT
              P.LASTNAME
    ,        P.FIRSTNAME
    ,        T.LANGUAGEID
    ,        T.TEST_TYPE
    ,        T.END_DATE
    ,        T.SCORE1
    ,        T.SCORE2
    FROM        PS_TEST_SCORES     T
    ,        PS_PERSONNEL           P
    WHERE        PS_TEST_SCORE.SSN     = PS_PERSONNEL.SSN
    AND        T.SCORE1           >= '2'
    AND       T.SCORE2          >= '2'
    AND        T.END_DATE           between to_date ( '01-jan-2009 00:00:00'
                                    , 'dd-mon-yyyy hh24:mi:ss'
                        and      to_date ( '28-jan-2011 00:00:00'
                                  , 'dd-mon-yyyy hh24:mi:ss'
    ORDER BY  P.LASTNAME;Now you do have a join condition:
    WHERE        PS_TEST_SCORE.SSN     = PS_PERSONNEL.SSNso that looks much better. In all the other conditions, you referred to the tables by their aliases, t and p, and not by their real names. You need to do that in this new condition, too:
    WHERE        T.SSN     = P.SSN
    now I get "PS_PERSONNEL.SSN invalid identifier"?
    I ran a query to see what the constraint types are.. PK, FK?? on the tables and there is no PK or FK they all say "C" would that affect the join?
    select *
    from all_constraints
    WHERE owner = 'OWNER' and TABLE_NAME LIKE 'PS\_%' ESCAPE '\'
    order by table_name, constraint_type;constraint_type='C' means a CHECK constraint, which has nothing to do with joins.
    constraint_type='R' indicates a referential integrity constraint, but that, at best, only hints at what a correct join condition might be.
    No kidding: if you want help, the best thing is to post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.

  • Report SUM not working (PL\SQL returning SQL query) using APEX_COLLECTION

    I have a simple query
    - select ename,sal from emp
    (In the Report attribute - SUM property is checked)
    I am getting the Report total SUM correctly...
    Now I am using the apex_collection object to display the same report.
    return select c001,c002 from apex_collections where collection_name = ''EMP'';
    c001 - ename
    c002 - sal (for this column - I am using Report total - SUM field is checked)
    ---- Issue is Report total SUM - is always displayed as 0. (actual sum is not coming).
    appreciate if I can get some input on this. I have tried a lot but no success..
    thanks,
    deepak

    Hi again
    Just checked a similar report test I did a while ago, and my query is:
    SELECT c001 MyText, TO_NUMBER(c002) MyNumber
    FROM HTMLDB_COLLECTIONS
    WHERE COLLECTION_NAME = 'ATD'
    So, you should use TO_NUMBER(c002)
    Andy

  • How to update multiple rows in one query using php

    i am new to this can any one help me how to update multiple rows at a time i am doing an school attendance page

    Often the situation is such that you have multiple courses across a range of dates.So students may take more than one course, and you need to track attendance for each course date. The following graphic demonstrates this:
    In such a situation, you need four database tables as follows:
    students (student_id, student_name, etc.)
    courses (course_id, course_name, etc.)
    students_courses (student_id, course_id)
    attendance (student_id, course_id, dater)
    A fifth table may also be needed to define the dates of courses, but you may also be able to build this array programmatically by using PHP's robust date functions, which can give you, for instance, all the Tuesdays and Thursdays between a start date and end date.
    The students_courses table simply keeps track of which students are taking which courses, so it has just two columns for the primary keys of both of the main tables. The attendance table is similar, but it also includes a date field. The following view of the attendance table demonstrates this:
    So if David's solution does cover your needs, consider yourself lucky, because this could quickly grow from a beginner-appropriate project to a moderately advanced one.

  • Number of total rows returned by a ref cursor without using FETCH

    Hi. How can we get the total number of rows returned by a ref cursor without doing the FETCH? I mean, if you use %ROWCOUNT, it only returns the current row number being returned in every fetch. This is not what I want. My purpose is to determine if my query using ref cursor returns greater than zero total rows without using fetch. Thanks.

    As John pointed out in the thread you linked to, the only way to know how many rows a query will return is to actually fetch all the rows. Oracle doesn't know how many rows a query is going to return until it actually fetches the last row.
    Plus, assuming the default transaction isolation level, if you run the same query multiple times in succession, there is no guarantee that the results will be the same.
    If you just want to know whether a query will return a nonzero number of rows, why not just write the code to assume that it returns at least 1 row and handle the zero row result as an exception.
    Justin

  • Req. the script for sending the rows returned by a query to my mail id.

    Hi ,
    Can anyone send me the script, for this thing.
    Actually i am working on production side, and i am executing the query which will return the rows of mview name which are not getting refreshed with the specified frequency. so i want those rows returned by query to be send to my mail id.
    Thanks a lot..
    With Regards
    Vedavathi.E

    Hello,
    Please review the following link;
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_smtp.htm#sthref15607
    Adith

Maybe you are looking for