So I have a database table that looks like -
MemberId LinkedMemberId
1 1
2 1
3 1
4 2
5 4
6 4
And I want to build a table value function where I can pass in 1, 2, 3, 4, 5 or 6 and it will return all of the values because they are linked.
Example -
I pass in 4, so I want 2, my LinkedMemberId. Now because I have 2, I also want the LinkedMemberId of 1. And now because I have 1, I also want the MemberIds associated with LinkedMemberId of 1.
Is there already an algorithm to get this kind of data?
You seem to be looking for a hierarchical query that retrives all parents of a given node. A typical approach is a recursive common-table-expression:
with cte as (
select LinkedMemberId, 1 lvl from mytable where memberId = ?
union all
select t.LinkedMemberId, c.lvl + 1
from mytable t
inner join cte c on c.LinkedMemberId = t.memberId
)
select * from cte
This gives you one row for each parent of the input memberId (which is represented by the ? in the query). As a bonus, the second column contains an incrementing integer value that represents the level of the parent in the hierarchy (starting at 1 for the first level parent).
Related
I'm using PostgreSQL 10, and I have the following structure:
A table Type with a foreign key to itself.
id name parent_id
1 namea Null
2 nameb Null
3 namea1 1
4 namea11 3
5 namea111 4
6 nameb1 2
7 nameb2 2
A table Item_Type for a Many to Many relation
id type_id item_id
1 1 1
2 3 2
3 5 3
4 7 4
Table Item which has M2M relation to Type.
id name
1 item1
2 item2
3 item3
4 item4
At this moment, I'm using an additional path field, which I calculate every time I make operations(crud) with Type.
I'm wondering if is not faster and easy to try to use the PostgreSQL recursion.
I checked the documentation but I didn't understand very well, because I get an error, and I don't understate why.
WITH RECURSIVE descendants AS (
SELECT id, name FROM Type WHERE id = 1
UNION
SELECT t.id, t.name, t.parent_id FROM Type AS t
INNER JOIN descendants AS d ON d.id = t.parent_id
) SELECT * FROM descendants;
ERROR: each UNION query must have the same number of columns
What I need - Giving a Type name:
1) Get all names/id for the requested Type and is descendants
2) Get all Item for the requested Type and is descendants, and the number of Item per Type and descendants
For example:
If the requested Type name is 'namea1', I should get for Type ids 1,3,4,5 and
for Item ids 1,2,3
The error says it all. Your union is divided between:
SELECT <2 fields> from Type ...
SELECT <3 fields> from Type JOIN Descendant ...
Simply select 3 fields on both halves:
WITH RECURSIVE descendants AS (
SELECT id, name, parent_id FROM Type WHERE id = 1
UNION
SELECT t.id, t.name, t.parent_id FROM Type AS t
INNER JOIN descendants AS d ON d.id = t.parent_id
) SELECT * FROM descendants;
The title of this post is probably not correct. I have a table like the one below and I need SQL that will select all the records that are related to a certain value. This is a "history" table that keeps track of ID values where I keep track of what an ID used to be. Record 1 splits into two and becomes 2 and 3, then maybe 2 and 3 merge together and become 4. For example:
OldID NewID
1 2
1 3
3 4
5 4
2 6
2 7
In the above example, record 1 has become 2 and 3. Record 4 is 3 and 5 merged together. Record 2 was part of 1 and has now split into 6 and 7.
So if we look at record NewID = 7, it is related to record 2, 6, and 1
NewID 4 is related to 3, 5, 1, and 2.
So in the end I need syntax that will select all records that were related in this way to NewID = X. Is this possible? Is this like a recursion?
Are you looking something like this?
declare #x int = 4
;with cte as (
select oldid, newid from table4 where newid = #x
union all
select t.oldid, t.newid from cte c inner join table4 t on c.OldId = t.newid
) select * from cte
I have a table where I have menus listed where I can insert and delete.
Structure goes like:-
ID Name ParentId
1 1. Home 0
2 2. Products 0
3 a. SubProduct1 2
4 b. SubProduct2 2
5 i. Subsub 4
6 ii. ...... 4
7 3. About 0
Top-level menu ParentId is always 0 as displayed in 1, 2 and 7.
Child level items would have ParentId of their parent for ex. Subproduct has 2 as its parentId.
When I delete menu item that time all level child item should be delete irrespective of there levels using SQL query.
There can be any number of levels
The levels can go upto subsubsubsub...... any number.
How about this query:
DECLARE #DelID INT
SET #DelID=1
;WITH T(xParent, xChild)AS
(
SELECT ParentID, ChildId FROM Table WHERE ParentID=#DelID
UNION ALL
SELECT ParentID, ChildId FROM TABLE INNER JOIN T ON ParentID=xChild
)
DELETE FROM TABLE WHERE ParentID IN (SELECT xParent FROM T)
You can use a common table expression to get all the heirarchy items from the item you want to delete to the end of the tree hten
;WITH ParentChildsTree
AS
(
SELECT ID, Name, ParentId
FROM MenuItems
WHERE Id = #itemToDelete
UNION ALL
SELECT ID, Name, ParentId
FROM ParentChildsTree c
INNER JOIN MenuItems t ON c.ParentId = t.Id
)
DELETE FROM MenuItems
WHERE ID IN (SELECT ID FROM ParentChildsTree);
Here is a Demo.
For example if you pass a parameter #itemToDelete = 4 to the query the the items with ids 2 and 4 will be deleted.
I have following data set
a b c
`1` 2 3
3 6 9
9 2 11
As you can see column a's first value is fixed (i.e. 1), but from second row it picks up the value of column c of previous record.
Column b's values are random and column c's value is calculated as c = a + b
I need to write a sql query which will select this data in above format. I tried writing using lag function but couldn't achieve.
Please help.
Edit :
Column b exists in table only, a and c needs to calculated based on the values of b.
Hanumant
SQL> select a
2 , b
3 , c
4 from dual
5 model
6 dimension by (0 i)
7 measures (0 a, 0 b, 0 c)
8 rules iterate (5)
9 ( a[iteration_number] = nvl(c[iteration_number-1],1)
10 , b[iteration_number] = ceil(dbms_random.value(0,10))
11 , c[iteration_number] = a[iteration_number] + b[iteration_number]
12 )
13 order by i
14 /
A B C
---------- ---------- ----------
1 4 5
5 8 13
13 8 21
21 2 23
23 10 33
5 rows selected.
Regards,
Rob.
Without knowing the relation between the rows ,how can we calculate the sum of the previous row a and b column to current row a column .I have created two more column id and parent in the table to find the relation between the two rows.
parent is the column which tell us about the previous row ,and id is the primary key of the row .
create table test1 (a number ,b number ,c number ,id number ,parent number);
Insert into TEST1 (A, B, C, ID) Values (1, 2, 3, 1);
Insert into TEST1 (B, PARENT, ID) Values (6, 1, 2);
Insert into TEST1 (B, PARENT, ID) Values (4, 2, 3);
WITH recursive (a, b, c,rn) AS
(SELECT a,b,c,id rn
FROM test1
WHERE parent IS NULL
UNION ALL
SELECT (rec.a+ rec.b) a
,t1.b b
,(rec.a+ rec.b+t1.b) c
,t1.id rn
FROM recursive rec,test1 t1
WHERE t1.parent = rec.rn
)
SELECT a,b,c
FROM recursive;
The WITH keyword defines the name recursive for the subquery that is to follow
WITH recursive (a, b, c,rn) AS
Next comes the first part of the named subquery
SELECT a,b,c,id rn
FROM test1
WHERE parent IS NULL
The named subquery is a UNION ALL of two queries. This, the first query, defines the starting point for the recursion. As in my CONNECT BY query, I want to know what is the start with record.
Next up is the part that was most confusing :
SELECT (rec.a+ rec.b) a
,t1.b b
,(rec.a+ rec.b+t1.b) c
,t1.id rn
FROM recursive rec,test1 t1
WHERE t1.parent = rec.rn
This is how it works :
WITH query: 1. The parent query executes:
SELECT a,b,c
FROM recursive;
This triggers execution of the named subquery. 2 The first query in the subquery's union executes, giving us a seed row with which to begin the recursion:
SELECT a,b,c,id rn
FROM test1
WHERE parent IS NULL
The seed row in this case will be for id =1 having parent is null. Let's refer to the seed row from here on out as the "new results", new in the sense that we haven't finished processing them yet.
The second query in the subquery's union executes:
SELECT (rec.a+ rec.b) a
,t1.b b
,(rec.a+ rec.b+t1.b) c
,t1.id rn
FROM recursive rec,test1 t1
WHERE t1.parent = rec.rn
Let's say I have an sql server table:
NumberTaken CompanyName
2 Fred 3 Fred 4 Fred 6 Fred 7 Fred 8 Fred 11 Fred
I need an efficient way to pass in a parameter [StartingNumber] and to count from [StartingNumber] sequentially until I find a number that is missing.
For example notice that 1, 5, 9 and 10 are missing from the table.
If I supplied the parameter [StartingNumber] = 1, it would check to see if 1 exists, if it does it would check to see if 2 exists and so on and so forth so 1 would be returned here.
If [StartNumber] = 6 the function would return 9.
In c# pseudo code it would basically be:
int ctr = [StartingNumber]
while([SELECT NumberTaken FROM tblNumbers Where NumberTaken = ctr] != null)
ctr++;
return ctr;
The problem with that code is that is seems really inefficient if there are thousands of numbers in the table. Also, I can write it in c# code or in a stored procedure whichever is more efficient.
Thanks for the help
Fine, if this question isn't going to be closed, I may as well Copy and paste my answer from the other one:
I called my table Blank, and used the following:
declare #StartOffset int = 2
; With Missing as (
select #StartOffset as N where not exists(select * from Blank where ID = #StartOffset)
), Sequence as (
select #StartOffset as N from Blank where ID = #StartOffset
union all
select b.ID from Blank b inner join Sequence s on b.ID = s.N + 1
)
select COALESCE((select N from Missing),(select MAX(N)+1 from Sequence))
You basically have two cases - either your starting value is missing (so the Missing CTE will contain one row), or it's present, so you count forwards using a recursive CTE (Sequence), and take the max from that and add 1
Tables:
create table Blank (
ID int not null,
Name varchar(20) not null
)
insert into Blank(ID,Name)
select 2 ,'Fred' union all
select 3 ,'Fred' union all
select 4 ,'Fred' union all
select 6 ,'Fred' union all
select 7 ,'Fred' union all
select 8 ,'Fred' union all
select 11 ,'Fred'
go
I would create a temp table containing all numbers from StartingNumber to EndNumber and LEFT JOIN to it to receive the list of rows not contained in the temp table.
If NumberTaken is indexed you could do it with a join on the same table:
select T.NumberTaken -1 as MISSING_NUMBER
from myTable T
left outer join myTable T1
on T.NumberTaken= T1.NumberTaken+1
where T1.NumberTaken is null and t.NumberTaken >= STARTING_NUMBER
order by T.NumberTaken
EDIT
Edited to get 1 too
1> select 1+ID as ID from #b as b
where not exists (select 1 from #b where ID = 1+b.ID)
2> go
ID
-----------
5
9
12
Take max(1+ID) and/or add your starting value to the where clause, depending on what you actually want.