Paging and count of rows
Hi,
I have a procedure doing paging and returning the count of rows:
As you see I used 2 select, one for paging and one for getting total row counts.
Is there a way to get rid of "SELECT count(*) into PO_TOTAL FROM TABLE1;"?
CREATE OR REPLACE PACKAGE BODY MYPACKAGE AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE SP_PAGING
PI_STARTID IN NUMBER,
PI_ENDID IN NUMBER,
PO_TOTAL OUT NUMBER,
CUR_OUT OUT T_CURSOR
IS
BEGIN
OPEN CUR_OUT FOR
SELECT *
FROM (SELECT row_.*, ROWNUM rownum_
FROM (
SELECT column1, column2, column3 FROM TABLE1
) row_
WHERE ROWNUM <= PI_ENDID)
WHERE rownum_ >= PI_STARTID;
SELECT count(*) into PO_TOTAL FROM TABLE1;
END SP_PAGING;
END MYPACKAGE;
Yes, I can reproduce that:
SQL> create table emp1 as select * from emp
2 /
Table created.
SQL> exec dbms_stats.gather_table_stats('SCOTT','EMP1');
PL/SQL procedure successfully completed.
SQL> EXPLAIN PLAN FOR
2 SELECT ename,
3 job,
4 sal,
5 cnt
6 FROM (
7 SELECT ename,
8 job,
9 sal,
10 count(*) over() cnt,
11 row_number() over(order by 1) rn
12 FROM emp1
13 )
14 WHERE rn BETWEEN 4 AND 9;
Explained.
SQL> @?\rdbms\admin\utlxpls
PLAN_TABLE_OUTPUT
Plan hash value: 1444408506
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 14 | 728 | 4 (25)| 00:00:01 |
|* 1 | VIEW | | 14 | 728 | 4 (25)| 00:00:01 |
| 2 | WINDOW BUFFER | | 14 | 252 | 4 (25)| 00:00:01 |
| 3 | TABLE ACCESS FULL| EMP1 | 14 | 252 | 3 (0)| 00:00:01 |
PLAN_TABLE_OUTPUT
Predicate Information (identified by operation id):
1 - filter("RN">=4 AND "RN"<=9)
15 rows selected.
SQL> EXPLAIN PLAN FOR
2 SELECT *
3 FROM (SELECT row_.*, ROWNUM rownum_
4 FROM (
5 SELECT ename,job,sal, count(*) over() FROM emp1
6 ) row_
7 WHERE ROWNUM <= 9)
8 WHERE rownum_ >= 4;
Explained.
SQL> @?\rdbms\admin\utlxpls
PLAN_TABLE_OUTPUT
Plan hash value: 519025698
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 9 | 468 | 2 (0)| 00:00:01 |
|* 1 | VIEW | | 9 | 468 | 2 (0)| 00:00:01 |
|* 2 | COUNT STOPKEY | | | | | |
| 3 | VIEW | | 9 | 351 | 2 (0)| 00:00:01 |
| 4 | WINDOW BUFFER | | 9 | 162 | 2 (0)| 00:00:01 |
| 5 | TABLE ACCESS FULL| EMP1 | 9 | 162 | 2 (0)| 00:00:01 |
PLAN_TABLE_OUTPUT
Predicate Information (identified by operation id):
1 - filter("ROWNUM_">=4)
2 - filter(ROWNUM<=9)
18 rows selected.
SQL> However, you interpreted it incorrectly. Your query will still fetch all rows in TABLE1. Optimizer is smart enough to stop creating window buffer after 9 rows and that is what you see 9 in explain plan, while my query builds 14 row window buffer and then filters. So your query will be a bit faster.
SY.
Edited by: Solomon Yakobson on Jan 25, 2009 2:51 PM
Similar Messages
-
The best way to do paging and get total rows count given a sql statement
Hi,
Just got a quick question.... what is the best way to do paging as well as the total rows count given by a sql statement.
e.g. "select * from emp"
1. I need to know the total row count for this statement.
2. I also need to do a 10 rows per page....
Is there a way to do it in a SINGLE statement for best performance?
Thanks experts.Sounds more like a "formatting" problem...
If Sql*plus is your reporting tool, check out the guide:
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a90842/toc.htm -
Table name and count of rows in that table through out the database
Hi All,
how to find the table_name and the number of rows in that table for all in a database.
Bhargava S Akula.Hi,
Something like this
create function table_count(
owner dba_tables.table_name%type
,table_name dba_tables.table_name%type)
return number
is
the_count number;
stmt varchar2(2000);
begin
stmt := 'select count(*) from ' || owner || '.' || table_name;
execute immediate stmt
into the_count;
return the_count;
exception
when others
then
return 0;
end table_count;
select owner, table_name, table_count(owner, table_name)
from dba_tables
where 1 = 2; -- remove this Regards
Peter -
Listing row length and count of rows
Hi,
I am trying to write a piece of code to fetch number of rows grouped monthly and running out of ideas, please help .. here is my requirement.
I have a flat file which contains table names and I need to query for the date column from those table, group it by month, number rows in that month. The generated output should contain the table_name, month, rowcount, and avg_row_length of that table.
Please advice.
Thanks.Hi
Good, I understand a lot better now. Sorry, I mis-read your first message.
You need to do some kind of dynamic SQL, that is, you want to run a query like:
select '&table_name'
, to_char(update_date, 'Mon-yyyy')
, count(*) row_count
from &table_name
group by TRUNC (update_date, 'MM')
ORDER BY TRUNC (update_date, 'MM');Does every table have a column called update_date, or is it called by different names in different tables? Either way, you can create a script (let's call it one_table.sql) that accepts an input parameter (the table name), and contains the query above.
Then, to call that for each of your tables, you vould create another script that contains:
-- Adjust SQL*Plus output settings
SET FEEDBACK OFF
SET PAGESIZE 0
SET VERIFY OFF
SPOOL combined_output.lst
-- Write common header line for the whole file
PROMPT table_name Month Rowcount avg_row_len
-- Run query on each table
@@one_table tab1
@@one_table tab2
@@one_table tab3
-- Finished.
SPOOL OFFThis will produce an output file like this:
table_name Month Rowcount avg_row_len
tab1 Jan-2008 20 100
tab1 Feb-2008 30 100
tab1 Mar-2008 40 100
tab2 Jan-2008 20 200
tab2 Feb-2008 50 200If you want to print the table name only on the first row, like this:
table_name Month Rowcount avg_row_len
tab1 Jan-2008 20 100
Feb-2008 30 100
Mar-2008 40 100
tab2 Jan-2008 20 200
Feb-2008 50 200You can make the query in one_table.sql a little more complicated: use ROW_NUMBER or ROWNUM to number the rows, and use CASE to print the table name on row #1, and nothing on the others.
Are you generating the list of tables yourself? If so, then instead of generating just the names, you might generate
@@one_table tab1
@@one_table tab2
@@one_table tab3or even the entire main script.
Sorry, I have to go now. See how far you can get with this, and post again if you have problems. -
Total count and count based on column value
Primaryid Id Status
1 50 1
2 50 1
3 50 1
4 50 3
5 50 2
6 50 1
7 51 1
8 51 2Im looking for a query which returns total count of rows for id 50 and count of rows with status 1
something like
Id count_total count_total_status1
50 6 4
51 2 1Any suggestion ?SQL> select * from t4;
PID ID STATUS
1 50 1
2 50 1
3 50 1
4 50 3
5 50 2
6 50 1
7 51 1
8 51 2
已选择8行。
SQL> select distinct id,count(id),sum(decode(status,1,1,0)) from t4 group by id;
ID COUNT(ID) SUM(DECODE(STATUS,1,1,0))
51 2 1
50 6 4 -
Hello everyone,
I am using the following MDX query on one of my SSRS report.
SELECT NON EMPTY { [Measures].[Days Outstanding], [Measures].[Amt] } ON COLUMNS,
NON EMPTY { ([Customer].[Customer].[Customer Key].ALLMEMBERS) }
HAVING [Measures].[ Days Outstanding] > 60
DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS
FROM ( SELECT ( STRTOSET(@Location, CONSTRAINED)) ON COLUMNS
FROM ( SELECT ( {[Date].[Fiscal Period].&[2014-06]}) ON COLUMNS
FROM [Model]))
Over here, the data is being filtered always for current month and for a location that is being selected by user from a report selection parameter.
I would like to get the count of total no. of customers and sum of the amount measure.
When I am using them in calculated members it gives incorrect values. It considers all records (ignores the sub-select statements) instead of only the records of current month and selected location.
I also tried with EXISTING keyword in calculated members but there is not difference in output. Finally, I manage the same at SSRS level.
Can anybody please advise what are the ways to get the required sum of [Measures].[Amt] and count of [Customer].[Customer].[Customer Key].ALLMEMBERS dimension?
Also, does it make any difference if I manage it as SSRS level and not at MDX query level?
Any help would be much appreciated.
Thanks, Ankit Shah
Inkey Solutions, India.
Microsoft Certified Business Management Solutions Professionals
http://www.inkeysolutions.com/MicrosoftDynamicsCRM.htmlCan anybody please advise what are the ways to get the required sum of [Measures].[Amt] and count of [Customer].[Customer].[Customer Key].ALLMEMBERS dimension?
Also, does it make any difference if I manage it as SSRS level and not at MDX query level?
Hi Ankit,
We can use SUM function and COUNT function to sum of [Measures].[Amt] and count of [Customer].[Customer].[Customer Key].ALLMEMBERS dimension. Here is a sample query for you reference.
WITH MEMBER [measures].[SumValue] AS
SUM([Customer].[Customer].ALLMEMBERS,[Measures].[Internet Sales Amount])
MEMBER [measures].[CountValue] AS
COUNT([Customer].[Customer].ALLMEMBERS)
MEMBER [Measures].[DimensionName] AS [Customer].NAME
SELECT {[Measures].[DimensionName],[measures].[SumValue],[measures].[CountValue]} ON 0
FROM [Adventure Works]
Besides, you ask that does it make any difference if I manage it as SSRS level and not at MDX query level. I don't thinks it will make much difference. The total time to generate a reporting server report (RDL) can be divided into 3 elements:Time to retrieve
the data (TimeDataRetrieval);Time to process the report (TimeProcessing);Time to render the report (TimeRendering). If you manage it on MDX query level, then the TimeDataRetrieval might a little longer. If you manage it on report level, then the TimeProcessing
or TimeRendering time might a little longer. You can test it on you report with following query:
SELECT Itempath, TimeStart,TimeDataRetrieval + TimeProcessing + TimeRendering as [total time],
TimeDataRetrieval, TimeProcessing, TimeRendering, ByteCount, [RowCount],Source
FROM ExecutionLog3
WHERE itempath like '%reportname'
Regards,
Charlie Liao
TechNet Community Support -
Count of rows from different tables.
Hi Friends,
I have 4 tables with a common column name "ID". I would like to get the count of rows from all the four tables which has the same ID.
Ex
select count(a.id) from table1 a,table2 b,table3 c,table4 d where a.id=b.id=c.id=d.id=5;
please suggest me some solutionmay be thsi?
select count(a.id) from table1 a,table2 b,table3 c,table4 d
where a.id=b.id and a.id=c.id and a.id=d.id and a.id=5; -
Hi Everyone,
I have a table Table1
Table1: ID, Name, Sales, Time
Sample data:
1, Loo, Y, 20-JUL-09 01.20.17.000000000 PM
2, Rey, Y, 20-JUL-09 01.20.17.000000000 PM
1, Loo, Y, 20-JUL-09 01.20.17.000000000 PM
1, Loo, Y, 20-JUL-09 01.20.17.000000000 PM
3, Bon, Y, 20-JUL-09 01.20.17.000000000 PM
1, Loo, Y, 19-JUL-09 01.20.17.000000000 PM
I want the result as:
1, 3
2, 1
3, 1
i.e employee with id 1 and count of his apperaince in the table where data is 20-JULY-09
Any suggestions and inputs are appreciated.
Thanks
KasiHi,
user10651875 wrote:
Thanks that worked.
If i want to change the query to get the ID which is having a count > 20 keeping all the other clauses, what should i modify?Do you mean you only want to diplay rows where count>20 (if any)?
Add a HAVING clause, immediately after the GROUP BY clause:
SELECT id
, COUNT (*) AS cnt
FROM table1
WHERE TRUNC (time) = DATE '2009-07-20'
GROUP BY id
HAVING COUNT (*) > 20;HAVING is similar to WHERE, but WHERE is evaluated before aggregate functions (like COUNT in this example) are compute. HAVING is evaluated after the aggregate functions are computed, therefore, you can use them in the HAVING clause. (In fact, you should never have a HAVING clause that doesn't use aggregate functions.) -
Count of rows of a table in header
Hi Experts,
I am stuck in a tricky scenario.
I need to get the count of rows of a table in a webi report in the header of the report.
And the count should change dynamically according to the filtering done on the table.
For eg.
If I have 10 countries in a table, so table has 10 rows.
Now the count on header should show 10.
Now if we filter the column to 5 countries, the count on the header should change to 5.
Any Idea's.
Regards,
GauravNops
It doesn't work.
Let me reframe my issue again:
I dragged country object on my report.
UK
US
JAPAN
CANADA
Now lets say in the report title, I write the formula as =Count(country)
It will give me 4.
Now I clicked on the column country and applied filter i.e. country = US ; UK
Now the block shows
UK
US
In the header the cell still shows 4, which I want to see as 2.
Any ideas....?
Thanks
Gaurav -
Calculating a count of rows where value matches another column value in the same table
Hi,
I'm struggling to do something in DAX that seems to me should be super easy (coming from a SQL world)!
That is to count all rows in column 1 where the value matches the current value for column 1?
E.g something like this:
[Col2]=Count of rows in [Col1] where value = this.[Col1]
Where the results are as in the table below:
Col1, Col2
A, 2
A, 2
B, 1
Anyone?
Martin Laukkanen
Nearbaseline blog - nearbaseline.com/blog
Bulk Edit and other Apps - nearbaseline.com/appsThanks, that's perfect!
I knew it had to be something so simple, but after spending over an hour banging my head against those exact functions I couldn't get anything working!
Martin Laukkanen
Nearbaseline blog - nearbaseline.com/blog
Bulk Edit and other Apps - nearbaseline.com/apps -
How to get count of rows for a table?
Hi,
How to get count of rows for a table and secondly, how can i have access to a particular cell in a table?
Regards,
DevashishHi Devashish,
WdContext.node<Your_node_name>().size() will give you the no: of rows.
This should be the node that is bound to the table's datasource property.
WdContext.node<Your_node_name>().get<node_name>ElementAt(index_value); will select the row at that particular index.
You can access an attribute of a particular row as
WdContext.node<Your_node_name>().get<node_name>ElementAt(index_value).get<attribute_name>();
Hope this helps,
Best Regards,
Nibu.
Message was edited by: Nibu Wilson -
How do i get the table_names and no of rows in a session
how do i write a select statement to
retrieve the all the table_names and number of rows in that table in a session.
for example i should get the output as below
tab_name no.of rows
tab1 40
tab2 50
tab3 25
thank u for the helpWhy? You do realize that this will force Oracle to do a full table-scan on every table in the schema, right? This will be horribly slow...
The PL/SQL approach would be something like this... You could also write a pipelined function to do this if you want to be able to do this in a SQL statement.
DECLARE
sqlStmt VARCHAR2(4000);
cnt NUMBER;
BEGIN
FOR x IN (SELECT * FROM user_tables)
LOOP
sqlStmt := 'SELECT COUNT(*) FROM ' || x.table_name || ';';
EXECUTE IMMEDIATE sqlStmt INTO cnt;
dbms_output.put_line( x.table_name || ': ' || to_char(cnt) );
END LOOP;
END;Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Hello,
I am doing a project that uses MS Access to access data about a baseball team . The MS Access Database provides the names, addresses, and age of the players. All the players are 12, 13, or 14 years old. I need to display the average age for the team on a
label, which was easy. The problem is that I also have to display the number of players who are 12, 13, and 14 years old and I have no idea how to do that.
Here is my code so far:
Public Class frmBaseball
Private Sub TeamBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TeamBindingNavigatorSaveItem.Click
Me.Validate()
Me.TeamBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.LittleLeagueDataSet)
End Sub
Private Sub frmBaseball_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'LittleLeagueDataSet.Team' table. You can move, or remove it, as needed.
Me.TeamTableAdapter.Fill(Me.LittleLeagueDataSet.Team)
End Sub
Private Sub btnAges_Click(sender As Object, e As EventArgs) Handles btnAges.Click
Dim strSql As String = "SELECT * FROM Team"
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data Source=e:\LittleLeague.accdb"
Dim odaTeam As New OleDb.OleDbDataAdapter(strSql, strPath)
Dim datAge As New DataTable
Dim intCount As Integer = 0
Dim intTotalAge As Integer
Dim decAverageAge As Decimal
odaTeam.Fill(datAge)
odaTeam.Dispose()
For intCount = 0 To datAge.Rows.Count - 1
intTotalAge += Convert.ToInt32(datAge.Rows(intCount)("Age"))
decAverageAge = Convert.ToDecimal(intTotalAge / datAge.Rows.Count)
Next
lblAverage.Visible = True
lblAverage.Text = "The average age of the team is " & decAverageAge.ToString("N2")
lbl12.Text = "The number of 12 year olds is "
lbl13.Text = "The number of 13 year olds is "
lbl14.Text = "The number of 14 year olds is "
lbl12.Visible = True
lbl13.Visible = True
lbl14.Visible = True
End Sub
End Class
I think I should use a For..Next loop but I don't know how to identify and match using this database, and then count how many repeated 12, 13, 14 years old there are.
Any help would be really appreciated.Hello,
Conceptually speaking you would group the data and count. Beings this is school work the demo below is a static example and not suitable for your assignment, its to show a point. Now if you have learned about LINQ and Lambda this logic can apply to your
question but need to work out using this your data which can be done. If not look at using SQL Grouping.
Example of SQL grouping and count
select country, count(country) as count from customers group by country
Module Module1
Public Sub GroupingDemo()
Dim dt As DataTable = SimulateLoadFromDatabase()
Dim TeamData = dt.AsEnumerable.GroupBy(
Function(student) student.Field(Of Integer)("Age")) _
.Select(Function(group) New With
Key .Value = group.Key,
Key .Info = group.OrderByDescending(
Function(x) x.Field(Of String)("Name"))}) _
.OrderBy(
Function(group) group.Info.First.Field(Of Integer)("age"))
Dim dictData As New Dictionary(Of String, String)
For Each group In TeamData
Console.WriteLine("Group: {0} count: {1} ", group.Value, group.Info.Count)
dictData.Add(group.Value.ToString, group.Info.Count.ToString)
' The following is not needed but good to show
For Each item In group.Info
Console.WriteLine(" {0} {1}",
item.Field(Of Integer)("Identifier"),
item.Field(Of String)("Name"))
Next
Next group
Console.WriteLine()
Console.WriteLine("This data can be used to populate control text")
For Each Item As KeyValuePair(Of String, String) In dictData
Console.WriteLine("{0} {1}", Item.Key, Item.Value)
Next
End Sub
Private Function SimulateLoadFromDatabase() As DataTable
Dim dt As New DataTable With {.TableName = "MyTable"}
dt.Columns.Add(New DataColumn With {.ColumnName = "Identifier", .DataType = GetType(Int32),
.AutoIncrement = True, .AutoIncrementSeed = 1})
dt.Columns.Add(New DataColumn With {.ColumnName = "Name", .DataType = GetType(String)})
dt.Columns.Add(New DataColumn With {.ColumnName = "Age", .DataType = GetType(Int32)})
dt.Rows.Add(New Object() {Nothing, "Bill", 13})
dt.Rows.Add(New Object() {Nothing, "Karen", 14})
dt.Rows.Add(New Object() {Nothing, "Jim", 13})
dt.Rows.Add(New Object() {Nothing, "Paul", 15})
dt.Rows.Add(New Object() {Nothing, "Mike", 14})
dt.Rows.Add(New Object() {Nothing, "Jill", 13})
Return dt
End Function
End Module
Output in the IDE output window
Group: 13 count: 3
3 Jim
6 Jill
1 Bill
Group: 14 count: 2
5 Mike
2 Karen
Group: 15 count: 1
4 Paul
This data can be used to populate control text
13 3
14 2
15 1
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. -
Count all rows of a Database table
I want to count all the rows of a table.
I have made correctly the connection with the database and all the other things (make a statement, make the query and the resultSet), I use the MySQL server v4.0.17
Here is the code I use:
int count=0;
String temp=null;
String query = "SELECT COUNT(*) FROM customers";//customers is my Database Table
try {
rs = stmt.executeQuery(query);
}//end try
catch(Exception exc) {
createFeatures.PlayErrorSound(registerRenter);
Optionpane.showMessageDialog(registerRenter,
"MESSAGE", "ERROR", JOptionPane.ERROR_MESSAGE);
}//end catch
try {
while(rs.next()) {
count++; //I use this variable in order to count the rows because the resultSet doesn't tell me the answer
countLine=rs.getInt(1);
}//end while
}//end try
catch(Exception exc) {
createFeatures.PlayErrorSound(registerRenter);
Optionpane.showMessageDialog(registerRenter,
"MESSAGE", "ERROR", JOptionPane.ERROR_MESSAGE);
}//end catch
count=count++; //i increase it aggain because if the rows are initial 0 i want to make it 1
temp = String.valueOf(count);//i use this command in order to display the result into a jtextfield
Any help is appreciated!!!!!This program will work just fine against mysql:
mport java.util.*;
import java.io.*;
import java.sql.*;
public class Test {
public static void main(String []args) {
String url= "jdbc:mysql://localhost/adatabase";
String query = "select count(*) from foo2";
String createQuery="create table foo2(f1 int)";
String dropQuery="drop table foo2";
String insertQuery="insert into foo2 values(1)";
Properties props = new Properties();
props.put("user", "auser");
props.put("password", "xxxxx");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Connecting to the msql server");
Connection con = DriverManager.getConnection(url, props);
Statement stmt = con.createStatement();
try {
stmt.executeUpdate(dropQuery);
} catch(SQLException e) {}
stmt.executeUpdate(createQuery);
stmt.executeUpdate(insertQuery);
stmt.executeUpdate(insertQuery);
PreparedStatement pstmt = con.prepareStatement(query);
System.out.println("***Executing a select");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("RowCount="+ rs.getString(1));
rs.close();
pstmt.close();
stmt.close();
con.close();
} catch(Exception e) {
System.out.println(e.getMessage());
} -
Hi!
I would like to get the count of rows in my ALV report . How to get the count of the rows ? Can anyone guide me in getting it dome please.
ThanksHi Gaddemmedi!
I am attaching the report as you had asked for. I have added the things you asked me to do and now I am getting the count on the top of the page. The problem is that though it shows me the count of the lines from the LAV report on top but when I try to filter the records in the report that count first of all dosent change and remain the same as the initial number of record though after filtering records reduce and over that the count lines keep on increasing I mean the count is shown in repeated lines afet lines. Kindly help please.
Thanks
*& Report ZSD_BILLING_HDR_TEXT_sum *
*& billing doc. and associated header text report *
*& CHANGE LOG *
*& jpoon 2007.08.03 Change request: DEVK905095 *
*& Move request: SD_1451_01 Requestor: Mona Fox *
*& FP14134 - original code. *
REPORT zsd_billing_hdr_text_sum MESSAGE-ID zsd NO STANDARD PAGE HEADING.
* For ALV usage
TYPE-POOLS: slis.
DATA: gs_layout TYPE slis_layout_alv,
tp_print TYPE slis_print_alv,
gt_sort TYPE slis_t_sortinfo_alv,
gt_events TYPE slis_t_event,
t_fieldcat TYPE slis_t_fieldcat_alv WITH HEADER LINE,
repid TYPE syrepid, " ABAP Program.
gt_list_top_of_page TYPE slis_t_listheader, " Top of page text.
alv_variant TYPE disvariant," Customize Disp. Variant
w_event type slis_alv_event.
DATA: w_field TYPE slis_fieldcat_alv.
TABLES: vbrk, vbrp, vbpa.
DATA SLIS_EV_AFTER_OUTPUT.
data: gs_list_top_of_page type slis_listheader.
*data: gt_list_top_of_page type slis_t_listheader.
* Definition of selection screen *
* By plant, storage location, sold-to customers, material and *
* posting date of the sales orders *
SELECTION-SCREEN BEGIN OF BLOCK one WITH FRAME TITLE text-001.
SELECT-OPTIONS: s_vbeln FOR vbrk-vbeln, " billing doc.
s_kunnr FOR vbpa-kunnr, " bill-to customer number.
s_werks FOR vbrp-werks, " line item plant.
s_fkdat FOR vbrk-fkdat, " billing date.
s_fkart FOR vbrk-fkart, " billing type.
s_vkorg FOR vbrk-vkorg. " sales org.
PARAMETERS: p_hold AS CHECKBOX.
SELECTION-SCREEN END OF BLOCK one.
* ALV display layout
SELECTION-SCREEN BEGIN OF BLOCK layout WITH FRAME TITLE text-003.
PARAMETERS: pa_vari TYPE slis_vari DEFAULT ' '. " Display variant.
SELECTION-SCREEN END OF BLOCK layout.
* Data Definitions *
* Storing Extracted Info.
TYPES: BEGIN OF t_extract,
vbeln TYPE vbeln_vf, " Sales order number.
posnr TYPE posnr, " line item
fkart TYPE fkart, " billing type.
vtext TYPE BEZEI20, " billing type description.
fkdat TYPE fkdat, " billing date.
werks TYPE werks_d, " line item plant.
werks_name1 TYPE name1, " plant description.
kunnr TYPE kunnr, " bill-to customer.
kunnr_name1 TYPE name1_gp, " bill-to description.
netwr TYPE netwr, " net value,invoice total $
zzflag TYPE boolean, " hold indicator
zzreason TYPE char30, " header text2 (reason)
zzuser TYPE ernam, " last changed by
zz_changed_date TYPE dats, " last changed date
zz_changed_time TYPE tims, " last changed time
END OF t_extract.
DATA: it_extract TYPE TABLE OF t_extract WITH HEADER LINE,
it_extract2 TYPE TABLE OF t_extract WITH HEADER LINE.
DATA: it_text TYPE TABLE OF tline WITH HEADER LINE.
DATA: wa_thead type thead.
DATA: w_tdname type TDOBNAME.
DATA: L_COUNT TYPE I.
* initialization
INITIALIZATION.
gs_layout-colwidth_optimize = 'X'.
tp_print-no_print_listinfos = 'X'.
tp_print-no_coverpage = 'X'.
PERFORM set_fieldcat.
PERFORM alv_eventtab_build USING:
** Event name Form to execute Event internal table
'TOP_OF_PAGE' 'TOP_OF_PAGE' gt_events[].
* Dropdown list for all created ALV layouts, global or user-specific
AT SELECTION-SCREEN ON VALUE-REQUEST FOR pa_vari.
PERFORM alv_variant_f4 CHANGING pa_vari.
* Main BODY of processing logic
START-OF-SELECTION.
IF s_vbeln IS INITIAL
AND s_kunnr IS INITIAL
AND s_werks IS INITIAL
AND s_fkdat IS INITIAL
AND s_fkart IS INITIAL
AND s_vkorg IS INITIAL.
MESSAGE i000 WITH text-037 ' ' ' ' ' '.
ELSE.
PERFORM extract_data.
ENDIF.
END-OF-SELECTION.
IF it_extract2[] IS INITIAL.
MESSAGE i000 WITH text-002 ' ' ' ' ' '.
ELSE.
* Build headings for report.
* PERFORM build_top_of_page USING gt_list_top_of_page[].
* describe table it_extract2 lines l_count.
*write :/ 'TOTAL NO OF ENTRIES', SY-VLINE, 32 L_COUNT.
PERFORM call_alv.
*write :/ 'TOTAL NO OF ENTRIES', SY-VLINE, 32 L_COUNT.
ENDIF.
*& Form EXTRACT_KEY_DATA
* Retreive the data for the report.
FORM extract_data.
CLEAR: it_extract. REFRESH: it_extract.
* read and select billing documents
IF p_hold IS INITIAL.
SELECT vbrk~vbeln vbrk~fkart vbrk~fkdat vbrk~netwr
vbrk~zzflag vbrk~zzreason vbrk~zzuser
vbrk~zz_changed_date vbrk~zz_changed_time
vbrp~posnr vbrp~werks
INTO CORRESPONDING FIELDS OF TABLE it_extract
FROM vbrk INNER JOIN vbrp ON
vbrk~vbeln = vbrp~vbeln
WHERE vbrk~vbeln IN s_vbeln
AND vbrk~fkart IN s_fkart
AND vbrk~fkdat IN s_fkdat
AND vbrk~vkorg IN s_vkorg
AND vbrk~fksto NE 'X'
AND vbrp~werks IN s_werks.
ELSE.
* read 'held' documents only as per selection
SELECT vbrk~vbeln vbrk~fkart vbrk~fkdat vbrk~netwr
vbrk~zzflag vbrk~zzreason vbrk~zzuser
vbrk~zz_changed_date vbrk~zz_changed_time
vbrp~posnr vbrp~werks
INTO CORRESPONDING FIELDS OF TABLE it_extract
FROM vbrk INNER JOIN vbrp ON
vbrk~vbeln = vbrp~vbeln
WHERE vbrk~vbeln IN s_vbeln
AND vbrk~fkart IN s_fkart
AND vbrk~fkdat IN s_fkdat
AND vbrk~vkorg IN s_vkorg
AND vbrk~fksto NE 'X'
AND vbrk~zzflag = 'X'
AND vbrp~werks IN s_werks.
ENDIF.
IF sy-subrc <> 0.
MESSAGE i000 WITH text-002 ' ' ' ' ' '.
ENDIF.
CHECK sy-subrc = 0.
* only need first line item for this report.
SORT it_extract BY vbeln posnr.
DELETE ADJACENT DUPLICATES FROM it_extract COMPARING vbeln.
LOOP AT it_extract.
* Retrieve and select by sales order bill-to on header level
* as well as lookup bill-to customer name/description
SELECT SINGLE kunnr FROM vbpa INTO it_extract-kunnr
WHERE vbeln = it_extract-vbeln
AND posnr = '000000'
AND parvw = 'RE'.
IF it_extract-kunnr IN s_kunnr.
it_extract-kunnr_name1 = zcl_kna1=>get_name1( it_extract-kunnr ).
ELSE.
DELETE it_extract.
CONTINUE.
ENDIF.
* lookup billing type description
SELECT SINGLE vtext FROM tvfkt
INTO it_extract-vtext
WHERE spras = sy-langu
AND fkart = it_extract-fkart.
IF sy-subrc <> 0.
clear it_extract-vtext.
ENDIF.
* lookup plant description
SELECT SINGLE name1 FROM t001w
INTO it_extract-werks_name1
WHERE werks = it_extract-werks.
IF sy-subrc <> 0.
clear it_extract-werks_name1.
ENDIF.
MOVE-CORRESPONDING it_extract TO it_extract2.
APPEND it_extract2.
ENDLOOP.
describe table it_extract2 lines l_count.
ENDFORM. " EXTRACT_DATA
*& Form SET_FIELDCAT
* Create the field catalogue.
FORM set_fieldcat .
*CLEAR W_EVENT.
*W_EVENT-FORM = SLIS_EV_AFTER_OUTPUT.
*W_EVENT-NAME = SLIS_EV_AFTER_LINE_OUTPUT.
*APPEND W_EVENT TO GT_EVENTS.
CLEAR w_field.
CLEAR t_fieldcat. REFRESH t_fieldcat.
w_field-col_pos = 1.
w_field-fieldname = 'ZZFLAG'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Hold Printing'(005).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 2.
w_field-fieldname = 'ZZREASON'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Reason'(036).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 3 .
w_field-fieldname = 'VBELN'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Billing Doc'(028).
w_field-emphasize = 'X'.
w_field-hotspot = 'X'.
APPEND w_field TO t_fieldcat.
CLEAR w_field.
w_field-col_pos = 4 .
w_field-fieldname = 'VTEXT'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Type Description'(030).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 5 .
w_field-fieldname = 'FKDAT'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Billing Date'(031).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 6 .
w_field-fieldname = 'WERKS'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Plant'(012).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 7 .
w_field-fieldname = 'WERKS_NAME1'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Plant Description'(032).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 8.
w_field-fieldname = 'KUNNR'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Bill-to Customer'(033).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 9 .
w_field-fieldname = 'KUNNR_NAME1'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Bill-to Description'(034).
w_field-emphasize = 'X'.
w_field-hotspot = 'X'.
APPEND w_field TO t_fieldcat.
CLEAR w_field.
w_field-col_pos = 10 .
w_field-fieldname = 'NETWR'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Invoice Amount'(035).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 11 .
w_field-fieldname = 'ZZUSER'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Changed By'.
APPEND w_field TO t_fieldcat.
w_field-col_pos = 12 .
w_field-fieldname = 'ZZ_CHANGED_DATE'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Last Changed Date'(006).
APPEND w_field TO t_fieldcat.
w_field-col_pos = 13 .
w_field-fieldname = 'ZZ_CHANGED_TIME'.
w_field-tabname = 'IT_EXTRACT2'.
w_field-seltext_l = 'Last Changed Time'(007).
APPEND w_field TO t_fieldcat.
* W_event-NAME = slis_ev_end_of_list.
* W_event-FORM = 'END_OF_LIST'.
* APPEND W_event TO GT_EVENTS.
* CLEAR W_event .
* w_field-col_pos = 14 .
* w_field-fieldname = 'COUNT'.
* w_field-tabname = 'IT_EXTRACT2'.
* w_field-seltext_l = 'COUNT'.
* APPEND w_field TO t_fieldcat.
ENDFORM. " SET_FIELDCAT
*& Form CALL_ALV
* Call the ALV Grid function.
FORM call_alv .
SORT it_extract BY vbeln.
* repid is necessary since the ALV F.M. does not work properly with
* sy-repid.
repid = sy-repid.
alv_variant-variant = pa_vari.
alv_variant-report = sy-repid.
alv_variant-username = sy-uname.
CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
EXPORTING
i_callback_program = repid
i_callback_user_command = 'USER_COMMAND'
is_layout = gs_layout
it_fieldcat = t_fieldcat[]
it_sort = gt_sort[]
i_default = 'X'
i_save = 'A'
is_variant = alv_variant
it_events = gt_events[]
is_print = tp_print
TABLES
t_outtab = it_extract2
EXCEPTIONS
program_error = 1
OTHERS = 2.
write :/ 'TOTAL NO OF ENTRIES', SY-VLINE, 32 L_COUNT.
IF sy-subrc NE 0.
MESSAGE w000 WITH text-004 ' ' ' ' ' '.
ENDIF.
ENDFORM. " CALL_ALV
*& Form alv_eventtab_build
* Pass list of events to be triggered by the ALV function module
FORM alv_eventtab_build USING u_name TYPE slis_alv_event-name
u_form TYPE slis_alv_event-form
alv_lt_events TYPE slis_t_event.
DATA: ls_event TYPE slis_alv_event. " structure for event handling
ls_event-name = u_name.
ls_event-form = u_form.
APPEND ls_event TO alv_lt_events.
ENDFORM. " alv_eventtab_build
* FORM TOP_OF_PAGE *
FORM top_of_page.
*gs_list_top_of_page-type = 'H'.
GS_LIST_TOP_OF_PAGE-INFO = L_COUNT.
APPEND GS_LIST_TOP_OF_PAGE TO GT_LIST_TOP_OF_PAGE.
CALL FUNCTION 'REUSE_ALV_COMMENTARY_WRITE'
EXPORTING
i_logo = 'NEWALTA_LOGO'
it_list_commentary = gt_list_top_of_page.
ENDFORM. " TOP_OF_PAGE
*& Form user_command
* Process the user command.
* -->R_UCOMM User command
* -->RS_SELFIELD Field selected
FORM user_command USING r_ucomm LIKE sy-ucomm
rs_selfield TYPE slis_selfield.
DATA: ltp_vbeln TYPE vbeln. " Sales document number.
CASE r_ucomm.
WHEN '&IC1'.
IF ( rs_selfield-fieldname = 'VBELN'
OR rs_selfield-fieldname = 'BILL_VBELN' )
AND rs_selfield-value IS NOT INITIAL. " Display sales document.
ltp_vbeln = rs_selfield-value.
zcl_sales_doc=>display( ltp_vbeln ).
ENDIF.
ENDCASE.
ENDFORM. "user_command
*& Form alv_v-ariant_f4
* Get the display variant.
* <--CTP_VARI Variant name
FORM alv_variant_f4 CHANGING ctp_vari TYPE slis_vari.
alv_variant-report = sy-repid. " Report ID
alv_variant-username = sy-uname. " User ID
CALL FUNCTION 'REUSE_ALV_VARIANT_F4'
EXPORTING
is_variant = alv_variant
i_save = 'A'
IMPORTING
es_variant = alv_variant
EXCEPTIONS
OTHERS = 1.
IF sy-subrc = 0.
ctp_vari = alv_variant-variant.
ENDIF.
ENDFORM. " alv_variant_f4
Maybe you are looking for
-
NFe com erro de assinatura - caracteres especiais
Bom dia, Algumas notas estão paradas com erro de assinatura por caracteres especiais nas descrições dos materiais. Fizemos a correção dos mesmos porém o GRC não recebe a atualização feita. A função J_1B_NFE_MS_REQUESTS_DATA também foi executada e mes
-
What is the significance of badi BBP_Create_PO_Back?
Hi Friends what is the significance of badi BBP_Create_PO_Back.? Thanks & Regards Kanni. Edited by: Kanni. on Jun 21, 2009 10:41 AM
-
in the weblogic 6.1; logging--http--format--extended the log only contain "#Fields: time cs-method cs-uri sc-status"! but i want the "#Fields: cs_ip time cs-method cs-uri sc-status...." how to do for it? thanks!!! please mail to [email protected]
-
Default email program setting won't stick
Hi, I use Outlook 2011 on my MacBook Pro, with OS 10.7.5. Often when I click a mailto link (or choose "send as email attachment" in Word), Mail launches instead of Outlook. I know how to change the setting for default email program in both Outlook an
-
Delivery picking by inputting picked quantity on batch input subitem
Hi All, For example: there is one item in a delivery document which is batch splitted into a subitem 900001. now i want to pick this delivery in my program. in foregroud, i need to input 'picking quantity' on subitem level(900001) so that the status