Hello I have tables sctucture with datas and 2 small questions.
CREATE TABLE [dbo].[Parent] (
[id] [int] NOT NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Child1] (
[Child1Id] [int] NOT NULL,
[ParentId] [int] NOT NULL,
[SomeData] [int] NOT NULL,
CONSTRAINT [PK_Child1] PRIMARY KEY CLUSTERED
(
[Child1Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Child2] (
[Child2Id] [int] NOT NULL,
[ParentId] [int] NOT NULL,
[SomeData] [int] NOT NULL,
CONSTRAINT [PK_Child2] PRIMARY KEY CLUSTERED
(
[Child2Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
INSERT INTO Parent VALUES(1,'Name 1')
INSERT INTO Parent VALUES(2,'Name 2')
INSERT INTO Parent VALUES(3,'Name 3')
INSERT INTO Parent VALUES(4,'Name 4')
INSERT INTO [Child1] VALUES(1,1,50)
INSERT INTO [Child1] VALUES(2,1,125)
INSERT INTO [Child1] VALUES(3,2,255)
INSERT INTO [Child2] VALUES(1,1,2)
INSERT INTO [Child2] VALUES(2,2,4)
INSERT INTO [Child2] VALUES(3,2,8)
INSERT INTO [Child2] VALUES(4,3,16)
-
How select all parets record with at least one child type in both tables.
I did next query
but I don’t know optimal way to show total count of this recordsSELECT p.Name, count(Child1) , count(Child2)
-
How select all parets records only that exist in both tables ?
SELECT p.Name, count(Child1) , count(Child2)
Thanks in Advice.
Query 1:
Query 2:
Note: If you just want to show the count of parent records, change
to
in either query.