count child records based on parent and date sql - sql

I am tryin to find the number of child records associated to a parent. This is based on 2 columns in the same table (master_ref for parent and ref for child). The difficulty i am finding is to only count the child if they have the same date_entered as the parent. Any help would be much appreciated.

Something like the following should work for you:
select parent.master_ref, COUNT(*)
from nodes parent join
nodes child
on child.ref = parent.master_ref
where parent.date = child.date
group by parent.master_ref;
You need to do a join in order to compare values between the parent and the child.

Assuming you have 3 tables like:
CREATE TABLE Parents (ID INT, date_entered DATE);
CREATE TABLE Children (ID INT, date_entered DATE);
CREATE TABLE Relation (master_ref INT, ref INT);
Following select statement should give you what you want:
SELECT p.ID, COUNT(*)
FROM Parents p
JOIN Relation r
ON p.ID = r.master_ref
JOIN Children c
ON c.ID = r.ref
WHERE c.date_entered = p.date_entered
GROUP BY p.ID
SQLFiddle with that code (without data): http://sqlfiddle.com/#!4/6e7d3/2/0

Related

Recursive query for postgresSQL parent/child

Asking for a little help on a recursive query syntax, and of course result.
As you will see I have a table with category parent and child ( a parent can have infinite children). Querying the category dictionary (linked to a real category)
And I want to return only the last child of every category tree
Updated my code, and information
EDIT
WITH RECURSIVE cat(id) AS (
SELECT
*
FROM
category_dictionary
LEFT JOIN category_dictionary.category ON category.id
WHERE
category.parent is NOT NULL
UNION
SELECT
*
FROM
cat
LEFT JOIN cat.category ON category.id
WHERE
category.parent is NOT NULL
)
SELECT
*
FROM
cat
Table information:
Category_dictionary is a table the join category on parameter category
Category is the main table with Parent entry.
Sample data:
category_dictionary entry:
ID : name (Men) : category_id
category entries:
category_id : name : parent (null or category_id)
As a result I want all the last child of each category entries, I mean the category that doesn't have child.
A recursive query is not needed to find the deepest children. Instead, one would look at entries that are not a parent (so no other child exists). Such entries ID is not included in the parent column.
You can then join this categories to other tables
SELECT *
FROM category cat
JOIN category_dictionary cat_dic ON cat.id = cat_dic.id
WHERE NOT EXISTS
(SELECT 1 FROM category cat2
WHERE cat2.parent = cat.id);

Count total number of rows where this.row is related with rows in another table

I have two simple tables, parents and children. I am trying to count the number of parents who have at least one child.
create table People(
id integer unique,
name varchar(120),
primary key (id)
);
create table children(
id integer unique,
name varchar(120),
parentId integer,
primary key(id),
foreign key (parentId) references People(id)
);
This is the code I tried but it gives me the total number of children instead:
select count(*)
from (people p join children ch on ch.parentid = p.id)
having count(ch.id) > 0;
I am trying to count the number of parents who have at least one children.
This should be as simple as:
SELECT COUNT(*)
FROM people p
WHERE EXISTS (SELECT 1 FROM children c WHERE c.parentid = p.id)
Using EXISTS is usually the most efficient way to check that something, well, exists.
You're close. You just need to make the check for children on a per-parent basis:
SELECT COUNT(*) AS parents_with_children
FROM (SELECT p.name, COUNT(c.id) AS num_children
FROM people p
JOIN children c ON c.parentid = p.id
GROUP BY p.name
HAVING COUNT(c.id) > 0) p
Demo on dbfiddle
SELECT COUNT(*),p.*
FROM People p JOIN children c ON c.parnetId=p.id
WHERE NOT c.parnetId IS NULL
GROUP BY (p.id)
(no need for having since it only joins existing children anyways)
select count(p.*)
from people p inner join children ch
on ch.parentid = p.id
You could try something like this,
SELECT COUNT(DISTINCT children.parentid)
FROM People
INNER JOIN children
ON children.parentid = people.id;
With EXISTS:
select count(distinct p.id) counter from people p
where exists (
select 1 from children
where parentid = p.id
)
or even better:
select count(distinct parentid) counter
from children
because all the info you need is in the table children, so just count the distinct values in column parentid

How do I do an SQL query based on a foreign key field?

I have the following tables:
people:
id, name
parent:
id, people_id, name
I have tried the following:
SELECT * FROM people
LEFT JOIN parent ON people.id = parent.people_id
WHERE parent.name != 'Carol';
How do I find all the people whose parent's name is not Carol?
You can try below code
select people.name from people
inner join parent on people.id=parent.people_id
where parent.name not in ('Carol')
If the two tables are to be queried by using Foreign Key.
If you want to get all records from one table that have some related entry in a second table then use Inner join
Select * from People INNER JOIN parent ON people.id = parent.people_id
WHERE parent.name <> 'Carol'
Similarly LEFT JOIN will get all records from the LEFT linked table but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL
First of all, why would you need two tables? why can't you have a single table named "Person" with ID,Name,ParentID columns
Where ParentID will be optional and reference the ID if it has got parent.
And run the following query
select * from PERSON where Name not like 'Carol%' and ParentID IS NOT NULL;
SELECT * FROM people WHERE EXISTS(SELECT 1 FROM parent WHERE people_id = id AND name <> 'Carol')
First of all the table structure you have taken restrict the future growth. Like in future if you want to add parents of your parents then it wont work in this table structure.
You can do like :
id | parent_id | people_name
Here you can make parent_id null for the parent and add parent_id as id for those who have parent. Here to retrieve you have to use SELF join(join in the same table)
`
Select * from people P
INNER JOIN parent PA ON PA.people_id = P._id
where PA.name not in ('Carol')
`
Difference between INNER JOIN and LEFT OUTER JOIN
is
1) INNER JOIN bring only similar data between two table
for ex if in people table parent_id table is nullable then it will not discard the complete row,but in case of LEFT OUTER JOIN it will bring all the rows from LEFT table as well as related table from right table.with all null in right joined row..

Query that selects the sum of all records that are referenced in another table

I have two tables, parent(id, name, child_id) and child(id, name, number) - not all parents may have childs and not all childs may have parents. I need a query that selects the sum of all records in child table and also selects the sum of only those records that have a parent and those that dont - that is determined by parent tables child_id column. How can this be done?
select
sum(c.number) AS sum AS a,
sum(all_child_records_that_have_a_parent) AS b,
sum(all_child_records_that_do not have a parent) AS c /*do not use a-b if possible*/
from
child c
The "all_child_records_that_have_a_parent" is the one i cant figure out :)
all_child_records_that_do not have a parent:
SELECT *
FROM child
WHERE id NOT IN (SELECT child_id FROM parent)
You can select distinct child ids from the parent table and outer join these to your child table. Then check for NULL.
select
sum(c.number) AS sum_all_c,
sum(case when x.child_id is not null then c.number end) AS sum_c_with_parent,
sum(case when x.child_id is null then c.number end) AS sum_c_without_parent
from child c
left outer join (select distinct child_id from parent) x on x.child_id = c.id;

How to get all child of a given id in SQL Server query

I have two tables in SQL Server database:
category(
itemid,
parentid
)
ArticleAssignedCategories(
categid,
artid
)
categid is a foreign key of itemid
I want to get count of artids and child of that for given itemid (child means categories with parentid of given itemid.)
For example; If given itemid = 1 and in table category have (3,1),(4,1)(5,3)
All of 3, 4, 5 are child of 1
Can anyone help me to write a good query?
Recursive queries can be done using CTE
with CTE(itemid, parentid)
as (
-- start with some category
select itemid, parentid
from category where itemid = <some_itemid>
union all
-- recursively add children
select c.itemid, c.parentid
from category c
join CTE on c.parentid = CTE.itemid
)
select count(*)
from ArticleAssignedCategories a
join CTE on CTE.itemid = a.categid
Here is the query. I hope this may help you
select b.artid,count(b.artid) from category a
inner join ArticleAssignedCategories b on a.itemid = b.artid
group by b.artid