Count child of every node in hier table reading source just once
Hi guys,
I'm trying to write a SQL statement to count how many child every node in a hierarchical table has.
I want to perform this operation reading source table only one time.
Following an example of source table:
CREATE TABLE TEST_HIER
ID NUMBER,
PID NUMBER
Insert into TEST_HIER
(ID, PID)
Values
(1, 0);
Insert into TEST_HIER
(ID, PID)
Values
(2, 1);
Insert into TEST_HIER
(ID, PID)
Values
(3, 1);
Insert into TEST_HIER
(ID, PID)
Values
(4, 2);
Insert into TEST_HIER
(ID, PID)
Values
(5, 3);
COMMIT;
And expected result is:
PID CHILD
0 1
1 2
2 1
3 1
Any idea?
Thanks a lot
Mauro
maybe a CONNECT BY clause is what you are looking for.
[code] SQL> select * from emp; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ---------- --------- ----- ----------- --------- --------- ------ 7566 JONES MANAGER 7839 02-Apr-1981 2975.00 1000.00 20 7902 FORD ANALYST 7566 03-Dec-1981 3000.00 20 7839 KING PRESIDENT 17-Nov-1981 5000.00 10 7698 BLAKE MANAGER 7839 01-May-1981 2850.00 30 7782 CLARK MANAGER 7839 09-Jun-1981 2450.00 10 7369 SMITH CLERK 7902 17-Dec-1980 800.00 20 7499 ALLEN SALESMAN 7698 20-Feb-1981 1600.00 300.00 30 7521 WARD SALESMAN 7698 22-Feb-1981 1250.00 500.00 30 7654 MARTIN SALESMAN 7698 28-Sep-1981 1250.00 1400.00 30 7788 SCOTT ANALYST 7566 09-Dec-1982 3000.00 20 7844 TURNER SALESMAN 7698 08-Sep-1981 1500.00 0.00 30 7876 ADAMS CLERK 7788 12-Jan-1983 1100.00 20 7900 JAMES CLERK 7698 03-Dec-1981 950.00 30 7934 MILLER CLERK 7782 23-Jan-1982 1300.00 10 7945 CINDY SALESMAN 7698 16-Jan-1983 1800.00 30 7950 TINA SALESMAN 7698 18-Jan-1983 1850.00 30 16 rows selected SQL> select level, substr(lpad(' ', level+2)||ename,1,20) employee, substr(lpad(' ', level+2)||job,1,12) job 2 from emp 3 start with job = 'PRESIDENT' 4 connect by prior empno = mgr; LEVEL EMPLOYEE JOB ---------- -------------------- ------------ 1 KING PRESIDENT 2 JONES MANAGER 3 FORD ANALYST 4 SMITH CLERK 3 SCOTT ANALYST 4 ADAMS CLERK 2 BLAKE MANAGER 3 ALLEN SALESMA 3 WARD SALESMA 3 MARTIN SALESMA 3 TURNER SALESMA 3 JAMES CLERK 3 CINDY SALESMA 3 TINA SALESMA 2 CLARK MANAGER 3 MILLER CLERK 16 rows selected SQL> [/code]
Similar Messages
-
How to add child node in Tree table programmetically
Jdev Version 11.1.1.4.0.
I have created tree table programmetically in bean.
I have to add child node to tree table component on button click event on page.
Please let me know how to do this in bean.
Regards,
KiranHow are you creating the tree pro-grammatically?
If you are adding a new node to underlying data structure and refresh the tree - the tree will get updated with the new data.
Thanks,
Navaneeth -
JTree cut and paste multiple child and ancestor nodes not function correct
Hello i'm creating a filebrowser for multimedia files (SDK 1.22) such as .jpg .gif .au .wav. (using Swing, JTree, DefaultMutableTreeNode)
The problem is I want to cut and paste single and multiple nodes (from current node til the last child "top-down") which partly functions:
single nodes and multiple nodes with only one folder per hierarchy level;
Not function:
- multiple folders in the same level -> the former order gets lost
- if there is a file (MMed. document) between folders (or after them) in the same level this file is put inside one of those
I tried much easier functions to cope with this problem but every time I solve one the "steps" the next problem appears...
The thing I don't want to do, is something like a LinkedList, Hashtable (to store the nodes)... because the MMed. filebrowser would need to much resources while browsing through a media library with (e.g.) thousands of files!
If someone has any idea to solve this problem I would be very pleased!
Thank you anyway by reading this ;)
// part of the code, if you want more detailed info
// @mail: [email protected]
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.tree.*;
// var declaration
static Enumeration en;
static DefaultMutableTreeNode jTreeModel, lastCopiedNode, dmt, insert, insertParent, insertSameFolder;
static String varCut;
static int index= 0;
static int counter = 0;
/* cut function */
if (actionCommand.equals ("cut"))
// get the selected node (DefaultMutableTreeNode)
lastCopiedNode = (DefaultMutableTreeNode) selPath.getLastPathComponent ();
// get the nodes in an Enumeration array (in top- down order)
en = dmt.preorderEnumeration();
// the way to make sure if it is a cut or a copied node
varCut = "cut";
/* paste function */
if (actionCommand.equals ("paste"))
// node is cut
if (varCut == "cut")
// is necessary for first time same folder case
insertParent = dmt;
// getting the nodes out of the array
while(en.hasMoreElements())
// cast the Object to DefaultMutableTreeNode
// and get stored (next) node
insert = (DefaultMutableTreeNode) en.nextElement();
// check if the node is a catalogue when getRepresentation()
// is a function of my node creating class (to know if it is
// a folder or a file)
if (insert.getRepresentation().equals("catalogue"))
// check if a "folder" node is inserted
if (index == 1)
counter = 0;
index = 0;
System.out.println ("***index and counter reset***");
// the node is in the same folder
// check if the folder is in the same hierarchy level
// -> in this case the insertParent has to remain
if (insert.getLevel() == insertParent.getLevel())
// this is necessary to get right parent folder
insertSameFolder = (Knoten) insert.getParent();
jTreeModel.insertNodeInto (insert, insertSameFolder, index);
System.out.println (">>>sameFolderCASE- insert"+counter+"> " + String.valueOf(insert) +
"\ninsertTest -> " + String.valueOf(insertTest)
// set insertParent folder to the new createded one
insertParent = insert;
index ++;
else // the node is a subfolder
// insertNode
jTreeModel.insertNodeInto (insert, insertParent, index);
// set insertParent folder to the new createded one
insertParent = insert;
System.out.println (">>>subFolderCASE- insertParent"+counter+"> " + String.valueOf(insertParent) +
"\ninsertParent -> " + String.valueOf(insertParent)
index ++;
else // the node is a file
// insertNode
jTreeModel.insertNodeInto (insert, insertParent, counter);
System.out.println (">>>fileCASE insert "+counter+"> " + String.valueOf(insert) +
"\ninsertParent -> " + String.valueOf(insertParent)
counter ++;
// reset index and counter for the next loop
index = 0;
counter = 0;
// reset cut var
varCut = null;
// remove the node (automatically deletes subfolders and files)
dmt.removeNodeFromParent (lastCopiedNode);
// if node is a copied one
if varCut == null)
// insert copied node the same way as for cut one's
// to make it possible to copy more than one node
}You need to use a recursive copy method to do this. Here's a simple example of the copy. To do a cut you need to do a copy and then delete the source.
import java.io.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.*;
import java.util.*;
public class CopyTree extends JFrame
Container cp;
JTree cTree;
JScrollPane spTree;
DefaultTreeModel cModel;
CNode cRoot;
JMenuBar menuBar = new JMenuBar();
JMenu editMenu = new JMenu("Edit");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
TreePath [] sourcePaths;
TreePath [] destPaths;
// =====================================================================
// constructors and public methods
CopyTree()
super("Copy Tree Example");
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent evt){System.exit(0);}});
// edit menu
copyItem.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e){mnuCopy();}});
editMenu.add(copyItem);
pasteItem.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e){mnuPaste();}});
editMenu.add(pasteItem);
menuBar.add(editMenu);
setJMenuBar(menuBar);
buildModel();
cp = getContentPane();
cTree = new JTree(cModel);
spTree = new JScrollPane(cTree);
cp.add(spTree, BorderLayout.CENTER);
pack();
static public void main(String [] args)
new CopyTree().show();
// =====================================================================
// private methods - User Interface
private void mnuCopy()
sourcePaths = cTree.getSelectionPaths();
private void mnuPaste()
TreePath sp, dp;
CNode sn,dn;
int i;
destPaths = cTree.getSelectionPaths();
if(1 == destPaths.length)
dp = destPaths[0];
for(i=0; i< sourcePaths.length;i++)
sp = sourcePaths;
if(sp.isDescendant(dp) || dp.isDescendant(sp))
JOptionPane.showMessageDialog
(null, "source and destinations overlap","Paste", JOptionPane.ERROR_MESSAGE);
return;
dn = (CNode)dp.getLastPathComponent(); // the node we will append our source to
for(i=0; i< sourcePaths.length;i++)
sn = (CNode)sourcePaths[i].getLastPathComponent();
copyNode(sn,dn);
else
JOptionPane.showMessageDialog
(null, "multiple destinations not allowed","Paste", JOptionPane.ERROR_MESSAGE);
// recursive copy method
private void copyNode(CNode sn, CNode dn)
int i;
CNode scn = new CNode(sn); // make a copy of the node
// insert it into the model
cModel.insertNodeInto(scn,dn,dn.getChildCount());
// copy its children
for(i = 0; i<sn.getChildCount();i++)
copyNode((CNode)sn.getChildAt(i),scn);
// ===================================================================
// private methods - just a sample tree
private void buildModel()
int k = 0;
cRoot = new CNode("root");
cModel = new DefaultTreeModel(cRoot);
CNode n1a = new CNode("n1a");
cModel.insertNodeInto(n1a,cRoot,k++);
CNode n1b = new CNode("n1b");
cModel.insertNodeInto(n1b,cRoot,k++);
CNode n1c = new CNode("n1c");
cModel.insertNodeInto(n1c,cRoot,k++);
CNode n1d = new CNode("n1d");
cModel.insertNodeInto(n1d,cRoot,k++);
k = 0;
CNode n1a1 = new CNode("n1a1");
cModel.insertNodeInto(n1a1,n1a,k++);
CNode n1a2 = new CNode("n1a2");
cModel.insertNodeInto(n1a2,n1a,k++);
CNode n1a3 = new CNode("n1a3");
cModel.insertNodeInto(n1a3,n1a,k++);
CNode n1a4 = new CNode("n1a4");
cModel.insertNodeInto(n1a4,n1a,k++);
k = 0;
CNode n1c1 = new CNode("n1c1");
cModel.insertNodeInto(n1c1,n1c,k++);
CNode n1c2 = new CNode("n1c2");
cModel.insertNodeInto(n1c2,n1c,k++);
// simple tree node with copy constructor
class CNode extends DefaultMutableTreeNode
private String name = "";
// default constructor
CNode(){this("");}
// new constructor
CNode(String n){super(n);}
// copy constructor
CNode(CNode c)
super(c.getName());
public String getName(){return (String)getUserObject();}
public String toString(){return getName();} -
How to count number of xml nodes , with JSTL XML api?
I am trying to count the number of nodes in the parsed xml by doing this:
<x:out select="count($doc/Items/Item)"/>
There are about 50 item nodes in the source xml, but I get the output as 0
Is this syntax correct?
I searched every where but couldn't find the xpath syntax to be used inside jstl xml tags, I was assuming that it's the same as the syntax used in xsltThank you for your reply, sorry I wasnt very clear with my question.
I want to count the number of nodes inside the jsp file , not inside the xslt file.
My xml file is something like this for example:
<?xml version="1.0" encoding="UTF-8"?>
<DocumentRootNode>
<Products>
<Item>1</Item>
<Item>2</Item>
<Item>3</Item>
<Products>
</DocumentRootNode>
I want the count of number of Item nodes , in the JSP file.
I'm doing something like this in the JSP but it gives 0 instead of 3:
<c:import url="source.xml" var="xml" charEncoding="UTF-8"/>
<x:parse doc="${xml}" var="xml_doc"/>
<x:out select="count($xml_doc/Products/Item)"/>
null -
View for a network node or link table
Can a view be used for a nework node or link table? The process sdo_net.validate_network hangs when I try to validate a network based on views for the node and link tables.
I am using a logical model. The sql statement (checking link/node relationship) that hangs is:
select count(a.link_id) from vlinks a
where not exists
select * from vnodes b
where b.node_id = a.start_node_id or b.node_id = a.end_node_id
I gather there is a concurrency issue with my links view because it joins a table with itself. I have a link table that has the start and end nodes defined on two records. Here is my view script:
create or replace view vlinks
(link_id, link_name, start_node_id, end_node_id, link_type, active, link_level, cost, parent_link_id)
as
select a.id, 'Link '||a.id, a.nodeid, b.nodeid, 'simple', 'Y',1,0,''
from vnodes a, vnodes b
where a.seq=1 and b.seq>1 and a.id = b.id
I can create tables from my views and validate them successfully through sdo_net.validate_nodes_schema, sdo_net.validate_links_schema, and sdo_net.validate_network.
I can analyze the network model through the Java API using the reachable nodes, shortest path, and spanning tree methods without any problems.
I guess I'll validate my view links by counting the total number of links and subtracting the number of links joined successfully at the start and end nodes - if 0 then all links are valid. E.g.:
select count(link_id) from
select link_id from vlinks
minus
select a.link_id from vlinks a, vnodes b, vnodes c
where a.start_node_id = b.node_id
and a.end_node_id = c.node_id -
Hi,
I have a model node and a table.
I want to do the next:
Depending of some attribute, I want to hide or show the element on the table and if the the element is hidden, dont count it(for the table's footer). Neither show the blank space on the table.
How could I do this?
Thanks,
F. CarranzaI thought that solution, but the problem is that I need the same node to show details at another view.
It's a node which elements are orders. I want to show in the table the pending orders, but in a DateNavigator I show the delivered orders, so I need the same node.
I only want to hide delivered orders at the table.
Thanks for your answer. -
CTE for Count the Binary Tree nodes
i have the table structure like this :
Create table #table(advId int identity(1,1),name nvarchar(100),Mode nvarchar(5),ReferId int )
insert into #table(name,Mode,ReferId)values('King','L',0)
insert into #table(name,Mode,ReferId)values('Fisher','L',1)
insert into #table(name,Mode,ReferId)values('Manasa','R',1)
insert into #table(name,Mode,ReferId)values('Deekshit','L',2)
insert into #table(name,Mode,ReferId)values('Sujai','R',2)
insert into #table(name,Mode,ReferId)values('Fedric','L',3)
insert into #table(name,Mode,ReferId)values('Bruce','R',3)
insert into #table(name,Mode,ReferId)values('paul','L',4)
insert into #table(name,Mode,ReferId)values('walker','R',4)
insert into #table(name,Mode,ReferId)values('Diesel','L',5)
insert into #table(name,Mode,ReferId)values('Jas','R',5)
insert into #table(name,Mode,ReferId)values('Edward','L',6)
insert into #table(name,Mode,ReferId)values('Lara','R',6)
select *from #table
How do i write the CTE for count the Binary tree nodes on level basis. Here is the example,
now,what i want to do is if i'm going to calculate the Count of the downline nodes.which means i want to calculate for '1' so the resultset which i'm expecting
count level mode
1 1 L
1 1 R
2 2 L
2 2 R
4 3 L
2 3 R
How do i acheive this,i have tried this
with cte (advId,ReferId,mode,Level)
as
select advId,ReferId,mode,0 as Level from #table where advid=1
union all
select a.advId,a.ReferId,a.mode ,Level+1 from #table as a inner join cte as b on b.advId=a.referId
select *From cte order by Level
i hope its clear. Thank youSee Itzik Ben-Gan examples for the subject
REATE TABLE Employees
empid int NOT NULL,
mgrid int NULL,
empname varchar(25) NOT NULL,
salary money NOT NULL,
CONSTRAINT PK_Employees PRIMARY KEY(empid),
CONSTRAINT FK_Employees_mgrid_empid
FOREIGN KEY(mgrid)
REFERENCES Employees(empid)
CREATE INDEX idx_nci_mgrid ON Employees(mgrid)
SET NOCOUNT ON
INSERT INTO Employees VALUES(1 , NULL, 'Nancy' , $10000.00)
INSERT INTO Employees VALUES(2 , 1 , 'Andrew' , $5000.00)
INSERT INTO Employees VALUES(3 , 1 , 'Janet' , $5000.00)
INSERT INTO Employees VALUES(4 , 1 , 'Margaret', $5000.00)
INSERT INTO Employees VALUES(5 , 2 , 'Steven' , $2500.00)
INSERT INTO Employees VALUES(6 , 2 , 'Michael' , $2500.00)
INSERT INTO Employees VALUES(7 , 3 , 'Robert' , $2500.00)
INSERT INTO Employees VALUES(8 , 3 , 'Laura' , $2500.00)
INSERT INTO Employees VALUES(9 , 3 , 'Ann' , $2500.00)
INSERT INTO Employees VALUES(10, 4 , 'Ina' , $2500.00)
INSERT INTO Employees VALUES(11, 7 , 'David' , $2000.00)
INSERT INTO Employees VALUES(12, 7 , 'Ron' , $2000.00)
INSERT INTO Employees VALUES(13, 7 , 'Dan' , $2000.00)
INSERT INTO Employees VALUES(14, 11 , 'James' , $1500.00)
The first request is probably the most common one:
returning an employee (for example, Robert whose empid=7)
and his/her subordinates in all levels.
The following CTE provides a solution to this request:
WITH EmpCTE(empid, empname, mgrid, lvl)
AS
-- Anchor Member (AM)
SELECT empid, empname, mgrid, 0
FROM Employees
WHERE empid = 7
UNION ALL
-- Recursive Member (RM)
SELECT E.empid, E.empname, E.mgrid, M.lvl+1
FROM Employees AS E
JOIN EmpCTE AS M
ON E.mgrid = M.empid
SELECT * FROM EmpCTE
Using this level counter you can limit the number of iterations
in the recursion. For example, the following CTE is used to return
all employees who are two levels below Janet:
WITH EmpCTEJanet(empid, empname, mgrid, lvl)
AS
SELECT empid, empname, mgrid, 0
FROM Employees
WHERE empid = 3
UNION ALL
SELECT E.empid, E.empname, E.mgrid, M.lvl+1
FROM Employees as E
JOIN EmpCTEJanet as M
ON E.mgrid = M.empid
WHERE lvl < 2
SELECT empid, empname
FROM EmpCTEJanet
WHERE lvl = 2
As mentioned earlier, CTEs can refer to
local variables that are defined within the same batch.
For example, to make the query more generic, you can use
variables instead of constants for employee ID and level:
DECLARE @empid AS INT, @lvl AS INT
SET @empid = 3 -- Janet
SET @lvl = 2 -- two levels
WITH EmpCTE(empid, empname, mgrid, lvl)
AS
SELECT empid, empname, mgrid, 0
FROM Employees
WHERE empid = @empid
UNION ALL
SELECT E.empid, E.empname, E.mgrid, M.lvl+1
FROM Employees as E
JOIN EmpCTE as M
ON E.mgrid = M.empid
WHERE lvl < @lvl
SELECT empid, empname
FROM EmpCTE
WHERE lvl = @lvl
Results generated thus far might be returned (but are not guaranteed to be),
and error 530 is generated. You might think of using the MAXRECURSION option
to implement the request to return employees who are two levels below
Janet using the MAXRECURSION hint instead of the filter in the recursive member
WITH EmpCTE(empid, empname, mgrid, lvl)
AS
SELECT empid, empname, mgrid, 0
FROM Employees
WHERE empid = 1
UNION ALL
SELECT E.empid, E.empname, E.mgrid, M.lvl+1
FROM Employees as E
JOIN EmpCTE as M
ON E.mgrid = M.empid
SELECT * FROM EmpCTE
OPTION (MAXRECURSION 2)
WITH EmpCTE(empid, empname, mgrid, lvl, sortcol)
AS
SELECT empid, empname, mgrid, 0,
CAST(empid AS VARBINARY(900))
FROM Employees
WHERE empid = 1
UNION ALL
SELECT E.empid, E.empname, E.mgrid, M.lvl+1,
CAST(sortcol + CAST(E.empid AS BINARY(4)) AS VARBINARY(900))
FROM Employees AS E
JOIN EmpCTE AS M
ON E.mgrid = M.empid
SELECT
REPLICATE(' | ', lvl)
+ '(' + (CAST(empid AS VARCHAR(10))) + ') '
+ empname AS empname
FROM EmpCTE
ORDER BY sortcol
(1) Nancy
| (2) Andrew
| | (5) Steven
| | (6) Michael
| (3) Janet
| | (7) Robert
| | | (11) David
| | | | (14) James
| | | (12) Ron
| | | (13) Dan
| | (8) Laura
| | (9) Ann
| (4) Margaret
| | (10) Ina
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
How to get the data from multiple nodes to one table
Hi All,
How to get the data from multiple nodes to one table.examples nodes are like A B C D E relation also maintained
Regards,
IndraHI Indra,
From Node A, get the values of the attributes as
lo_NodeA->GET_STATIC_ATTRIBUTES( IMPORTING STATIC_ATTRIBUTES = ls_attributesA ).
Similarily get all the node values from B, C, D and E.
Finally append all your ls records to the table.
Hope you are clear.
BR,
RAM. -
How do I add a cell count to the data already in my tables in Numbers '08?
I am using Numbers '08, Mac OS X 10.8.2
I have a spreadsheet with a number of different tables. Each table refers to a style of music and lists songs in that style. I want to count the number of songs in each table (bearing in mind that the first row in each table is a heading and would not be counted). I also want this number to automatically update each time a new song is added or removed. Is there are way of adding this number count into data that is already stored or would I need to start from scratch with a specific table style?Smiley
I would approach this a little differently, but there are more similarities than differences.
I would change the names of the list tables from Table 1, Table 2, etc. to Jazz, Pop, etc.
Column A would have the song number, Column B, the song name.
In Column A, I would write: =IF(LEN(B)>0, ROW()-1 & "."
That's all the programming for the data tables. You can insert and delete and sort to your heart's content.
For the statistics I would have a table named "Summary". In the Summary table you would list the genres in Column A and would calculate the number of songs for each genre in Column B. The calculation of titles per genre would be:
=COUNTA(INDIRECT(A&"::B"))
The calculation for the combined total in the Footer row would be:
=SUM(B)
Here's a screen shot:
As you add genre tables, just add rows to the Summary table and expand the genre list, filling the count formula down.
I suggest that if you want to try my way, that you do it with a little sample table, like the one I used, to see if the formulas all work in Numbers 08. If anything fails, report it and we can try to adapt it to the old program.
Regards,
Jerry -
How can I create an internal space from the border in every cell in a table?
How can I create an space between the text contents and the border inside in every cell in a table in Pages?
Change the Inset margin in the Inspector palette > T tab > Text
-
Error Expanding Database Node : ORA-00942 table or view does not exist
I just installed the ODT for Visual Studio.NET. It installed fine and I can connect to my databases. However, I am having trouble expanding adatabase node to see all of its object nodes (tables, views, ...). I get the ORA-00942 error when connecting with a user id and password used by an application. If I use my personall user id an password, I can expand the database node. What table or view is it looking for that it cannot find? Is this something that our DBA has prevented? Any ideas would be appreciated.
Only guessing, but I wouldn't expect an application id to have anything like the same rights as a normal id. I wouldn't expect it to have any rights to tables, just to stored procedures and/or views, but this would be up to the standards in your organisation. This will be something the DBA has done, probably granting the absolute minimum of rights to the application id. It might be looking for one of the system views, so if there's an option to ignore system objects try setting it.
-
How to make every coloum in a table/report searchable in an application???
I used the wirzed to make some applications based on some of my tables in the DB, but I when I typed a specific record in the search textbox, some them I can search, but some of them, they showed" data cannot be found",
I hope every coloum in my table can be searchable, just like I use the select command .
Any idea about this?
Thanks!
Message was edited by:
PeterCNI hope every column can be searched in my applications.
-
Select a count using the last entry of a table
I have a huge project for which I am trying to learn some PL/SQL.
Context:
Entry gets put into the Orders table. What I want to do is create a trigger( out of scope for this question) that takes the last entry's product ID number and performs a count of all the PID's that match it. Then I want to compare that number with a number in the ProductTransaction table.
I.e.
Orders ProductTransaction
OID TID
PID PurchaseCount
o_TID Price
etc.....
Last entry that gets put in contains
OID PID TID
4 100 2
ProductTransaction
TID PurchaseCount Price
2 10 100.00
What I want to do is if the last entry into the Orders table was the OID 4 then I want to count all PID=100 and determine if the PurchaseCount has been reached yet.
The only thing I can think of is the following, but it doesn't ensure that the last PID is what we are counting:
declare
v_countpid number;
begin
select
count(pid) into v_countpid
from
orders
where OID = (select last(oid) from orders);
dc
Im thinking something like the above which populates the v_countpid
and then taking another variable which is a select into which takes the last TID entered and comparing them in an if statement of some sort
Let me know your thoughts on this....They you both for your replies. I was pushing myself to stay up late last night and I guess I didn't included everything.
Here it goes.
The concept is to have someone buy a product lets say at 10 dollars and it will take 10 other people for you to finally get your product released to you.
So when I purhcase PRODUCT A and put the entry into the orders table it will be something like this:
OID = 1
PID = 101
TID = 2
TIMEOFPURCHASE=<timestamp>
etc........
Now once that is entered into the table I am going to have a trigger as an after insert that will count the total PID's in the table that match what I just put into it, as in this case it was PID=101. The count of PID=101 will then be matched against the ProductTransaction PurchaseCount field to determine if that product should be released to the person with the lowest timestamp.
So....
ProductTransaction
TID=2
PRICE=$10
PurchaseCount=10
ORDERS
OID PID TID TOP
1 101 2 3 am
2 101 2 5 am
3 30 1 12 pm
4 101 2 4 pm
Example. The last entry was OID=4 so it will count up the number of PID=101 and then that number is compared against ProductTransaction purchase count. If hasn't exceeded then nothing happens. If the number is matched then OID=1 is moved into the shipping table for processing.
Let me know if this still doesn't clarify, or if there is a better way to do this.... -
Procudure to count all the rows in a all tables in the schema
When I run the following store procedure to count all the rows in all the tables I crash my sql Plus editor:
CREATE OR REPLACE PROCEDURE TC_TABLEROWCOUNT(OWNER IN varchar2)
IS
row_count number;
cursor get_tab is
select table_name, num_rows
from all_tables
where owner='MAXDEV';
begin
dbms_output.put_line('Checking Record Counts for schema maxdev ');
FOR get_tab_rec IN get_tab LOOP
BEGIN
EXECUTE IMMEDIATE 'select count(*) from '||get_tab_rec.table_name
INTO row_count;
EXCEPTION WHEN OTHERS THEN
dbms_output.put_line('Error counting rows for table '
||get_tab_rec.table_name);
END;
END LOOP;
END;
What am I doing wrong.
Thanks for any help TonyThe boss gave me 5 pages of tables and wants to know how many row there are in each table. There is a problem of one DB being out of sync with another.
But I have managed to work the problem though.
here is the working code:
CREATE OR REPLACE PROCEDURE TC_TABLEROWCOUNT (
TableOwner IN varchar2)
IS
row_count number;
vTable varchar2(30);
v_sqlstmt varchar2(100);
cursor get_tab is
select table_name, num_rows
from all_tables
where owner = TableOwner;
begin
dbms_output.put_line('Checking Record Counts for schema maxdev ');
FOR get_tab_rec IN get_tab LOOP
vTable := get_tab_rec.table_name;
v_sqlstmt := 'SELECT count(*) from '||vTable;
EXECUTE IMMEDIATE v_sqlstmt into row_count;
dbms_output.put_line('Table '|| get_tab_rec.table_name || ' Row ' || row_count);
END LOOP;
END; -
COunt no of rows of all the tables
hai
Pls tell me COunt no of rows of all the tables in the user SOP
Output like this
Tablename rows
sen 31
van 45
etc
pls help
Sset serveroutput on size 100000 feedback off
declare
rs integer;
cur integer;
rp integer;
trs integer;
n integer;
un varchar2(30);
begin
dbms_output.put_line(rpad('Table Name',40)||' Number of Rows Created Date');
dbms_output.put_line(rpad('-',73,'-'));
cur:= dbms_sql.open_cursor;
for t in (select object_name, created from dba_objects where object_type='TABLE' and OWNER='SOP') loop
dbms_sql.parse(cur,'select count(*) from SOP.' || t.object_name, dbms_sql.v7);
dbms_sql.define_column(cur, 1, rs);
rp:= dbms_sql.execute(cur);
n:=dbms_sql.fetch_rows(cur);
dbms_sql.column_value(cur, 1, rs);
dbms_output.put_line(rpad(t.object_name,48,'.')||rpad(rs,15,'.')||t.created);
end loop;
dbms_sql.close_cursor(cur);
dbms_output.put_line(rpad('-',73,'-'));
end;
set serveroutput off feedback on feedback 6
Anyway or...
set serveroutput on size 100000 feedback off
declare
rs integer;
cur integer;
rp integer;
trs integer;
n integer;
un varchar2(30);
v_user varchar2(20);
begin
v_user := '&user';
dbms_output.put_line(rpad('Table Name',40)||' Number of Rows Created Date');
dbms_output.put_line(rpad('-',73,'-'));
cur:= dbms_sql.open_cursor;
for t in (select object_name, created from dba_objects where object_type='TABLE' and OWNER=v_user) loop
dbms_sql.parse(cur,'select count(*) from '|| v_user ||'.' || t.object_name, dbms_sql.v7);
dbms_sql.define_column(cur, 1, rs);
rp:= dbms_sql.execute(cur);
n:=dbms_sql.fetch_rows(cur);
dbms_sql.column_value(cur, 1, rs);
dbms_output.put_line(rpad(t.object_name,48,'.')||rpad(rs,15,'.')||t.created);
end loop;
dbms_sql.close_cursor(cur);
dbms_output.put_line(rpad('-',73,'-'));
end;
Enter value for user: TEST
old 11: v_user := '&user';
new 11: v_user := 'TEST';
Table Name Number of Rows Created Date
TEST_UPDATE2....................................1..............21-JAN-09
TEST_UPDATE.....................................1..............20-JAN-09
Maybe you are looking for
-
Jabber 9.2 and StartCallWithVideo set to false not taking
The StartCallWithVideo option doesn't seem to working in Jabber 9.2 (tried 9.2.0 and 9.2.2). Tried false and FALSE for value. The jabber-config file downloads fine and has all the settings below on PC and the DockedWindow is not visible so the settin
-
how can i connect iphone to itunes.. i want to restore because my finger mistakes that click Reset all content and setting.. so iphone are empty.. all foto and data lost, right.. how can i use my iphone again.
-
How to choose between CBR and 2-Pass VBR ?
Hi, I know alot of virtual ink has flowed about this topic, but I couldnt find the answer I need. I'm compressing an 83minute feature film to DVD. Source material is 10bit Uncompressed YUV from PAL DigiBeta, sent directly from FCP to Compressor. Comp
-
User domain\SPFservice is not authorized to perform request using authentication type Negotiate
Hi, I have installed WAP/SPF in the same domain via express installation. The SPF domain service account is sysadmin on the SPF database. The SPF domain service account is running as identity in IIS application pool. I have registered SPF in WAP v
-
Initializing a Zip File to non-First ZipEntry?
hi, i have zip Files that have 4000 zip Entries each. I need to have the ability to ID if a certain ZipEntry is in the file, and then open it directly and start reading from it. I posted about this last week, but i made the question more concise. Her