SQL Statement summarize missing employee certifications - sql

I am trying to create a report on tables that I can't modify and am not sure if this is even possible.
Using the script below, I am trying to get a query result of:
--Certification | Employee | Has Certification
--CPR | Santa Clause | Yes
--CPR | Rudolph | No
CREATE TABLE [dbo].[Certification]([Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Certification] PRIMARY KEY CLUSTERED ([Id] ASC));
CREATE TABLE [dbo].[Employee]([Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([Id] ASC));
CREATE TABLE [dbo].[EmployeeCertification]([Id] [int] IDENTITY(1,1) NOT NULL,
[CertificationID] [int] NOT NULL,
[EmployeeID] [int] NOT NULL,
CONSTRAINT [PK_EmployeeCertification] PRIMARY KEY CLUSTERED ([Id] ASC));
ALTER TABLE [dbo].[EmployeeCertification] WITH CHECK ADD CONSTRAINT
[FK_EmployeeCertification_Certification] FOREIGN KEY([CertificationID])
REFERENCES [dbo].[Certification] ([Id])
ALTER TABLE [dbo].[EmployeeCertification] CHECK CONSTRAINT
[FK_EmployeeCertification_Certification]
ALTER TABLE [dbo].[EmployeeCertification] WITH CHECK ADD CONSTRAINT
[FK_EmployeeCertification_Employee] FOREIGN KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([Id])
ALTER TABLE [dbo].[EmployeeCertification] CHECK CONSTRAINT
[FK_EmployeeCertification_Employee]
INSERT INTO Certification (Name) VALUES ('CPR');
INSERT INTO Employee (Name) VALUES ('Santa Clause'),('Rudolph');
INSERT INTO EmployeeCertification (CertificationID,EmployeeID) VALUES(1,1);

You can cross join employees and certifications to generate all possible combinations, then use a subquery to check whether each tuple exists in the bridge table:
select c.name as certification, e.name as employee,
case when exists (
select 1
from employeecertification ec
where ec.employeeid = e.id and ec.certificationid = c.id
) then 'Yes' else 'No' end as has_certification
from employee e
cross join certification c
This can also be done with a left join:
select c.name as certification, e.name as employee,
case ec.id is null then 'No' else 'Yes' end as has_certification
from employee e
cross join certification c
left join employeecertification ec on ec.employeeid = e.id and ec.certificationid = c.id

Related

SQL Server: select records, not linked to another table

I have a table:
CREATE TABLE [dbo].[CollectionSite]
(
[SiteCode] [nvarchar](32) NOT NULL,
[AddressId] [int] NOT NULL,
[RemittanceId] [int] NULL,
// additional columns
)
and a linked table:
CREATE TABLE [dbo].[CollectionSiteAddress]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](255) NULL,
[Address1] [nvarchar](255) NULL,
[Address2] [nvarchar](255) NULL,
[City] [nvarchar](128) NULL,
[State] [nvarchar](64) NULL,
[Zip] [nvarchar](32) NULL,
)
Relationship between these 2 tables:
ALTER TABLE [dbo].[CollectionSite] WITH CHECK
ADD CONSTRAINT [FK_CollectionSite_CollectionSiteAddress_AddressId]
FOREIGN KEY([AddressId]) REFERENCES [dbo].[CollectionSiteAddress] ([Id])
GO
ALTER TABLE [dbo].[CollectionSite] WITH CHECK
ADD CONSTRAINT [FK_CollectionSite_CollectionSiteAddress_RemittanceId]
FOREIGN KEY([RemittanceId]) REFERENCES [dbo].[CollectionSiteAddress] ([Id])
GO
I want to select all records from CollectionSiteAddress, which are not linked to CollectionSite (neither AddressId nor RemittanceId). Which request should I use?
I tried:
SELECT *
FROM CollectionSiteAddress
LEFT JOIN CollectionSite ON CollectionSiteAddress.Id = CollectionSite.AddressId
OR CollectionSiteAddress.Id = CollectionSite.RemittanceId
but it selects all records from CollectionSiteAddress
You are missing this WHERE clause:
WHERE CollectionSite.[SiteCode] IS NULL
because you want all the unmatched rows of CollectionSiteAddress.
I used the column [SiteCode] to check if it is NULL because it is not nullable in the definition of the table.
So you can write your query like this (shortened with aliases):
SELECT csa.*
FROM CollectionSiteAddress csa LEFT JOIN CollectionSite cs
ON csa.Id = cs.AddressId OR csa.Id = cs.RemittanceId
WHERE cs.[SiteCode] IS NULL
Or use NOT EXISTS:
SELECT csa.*
FROM CollectionSiteAddress csa
WHERE NOT EXISTS (
SELECT 1
FROM CollectionSite cs
WHERE csa.Id = cs.AddressId OR csa.Id = cs.RemittanceId
)

Referencing the primary table in a sub-query

I have tables with some relations:
create table Students
(
[id] uniqueidentifier not null,
primary key (id),
[group] uniqueidentifier FOREIGN KEY REFERENCES [Groups]([id]) not null,
[name] nvarchar(20),
[surname] nvarchar(20)
)
create table Books
(
[id] uniqueidentifier not null,
primary key (id),
[name] nvarchar(100) not null,
[pages] int not null,
[author] uniqueidentifier FOREIGN KEY REFERENCES [Authors]([id])
)
create table StudentsCards
(
[id] uniqueidentifier not null,
primary key (id),
[student] uniqueidentifier FOREIGN KEY REFERENCES [Students]([id])
)
create table RelationsBooksToStudentsCards
(
[book] uniqueidentifier FOREIGN KEY REFERENCES [Books]([id]) not null,
[students_card] uniqueidentifier FOREIGN KEY REFERENCES [StudentsCards]([id]) not null
)
And I have query which trying to get sum of pages by students:
SELECT
[id] AS student_id, [name], [surname],
(SELECT SUM(b.pages)
FROM Students AS s
INNER JOIN RelationsBooksToStudentsCards AS r ON (SELECT [id] FRM StudentsCards WHERE student = s.id) = r.students_card
INNER JOIN Books AS b ON r.book = b.id
WHERE s.id LIKE student_id)
FROM
Students
Question: what do I need to do to use student_id in the query? Because now I got an exception:
Invalid column name 'student_id'
Ah, it was easy:
select [id], [name], [surname], (SELECT sum(b.pages)
FROM Students as s
inner JOIN RelationsBooksToStudentsCards as r
ON (select [id] from StudentsCards where student = s.id) = r.students_card
inner JOIN Books as b
ON r.book = b.id
where s.id like myAlias.id) from Students as myAlias

SQL foreign key constraint with additional column value check

I have this situation
CREATE TABLE [dbo].[Customer]
(
Id INT IDENTITY(1,1) NOT NULL,
IsWholesaler BIT NOT NULL,
Name NVARCHAR(255) NOT NULL
)
CREATE TABLE [dbo].[WholesalerUser]
(
Id INT IDENTITY(1,1) NOT NULL,
CustomerId INT NOT NULL,
UserId INT NOT NULL
)
CREATE TABLE [dbo].[User]
(
Id INT IDENTITY(1,1) NOT NULL,
Name NVARCHAR(255)
)
One Customer which has IsWholesaler column set to true can have multiple users.
I have WholesalerUser table for this purpose but the Foreign key WholesalerUser.CustomerId is attached to Customer.Id but how to check the column IsWholesaler = 1 ?
Foreign key can be defined over several columns at once.
Add a column IsWholesaler to the WholesalerUser.
Add a check constraint to make sure that it is always 1.
Define foreign key over two columns (CustomerId, IsWholesaler).
To define such foreign key the Customer table should have either primary key as (ID, IsWholesaler), or a separate unique index on (ID, IsWholesaler).
Table Customer
CREATE TABLE [dbo].[Customer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[IsWholesaler] [bit] NOT NULL,
[Name] [nvarchar](255) NOT NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
Unique index to support foreign key constraint:
CREATE UNIQUE NONCLUSTERED INDEX [IX_ID_IsWholesaler] ON [dbo].[Customer]
(
[Id] ASC,
[IsWholesaler] ASC
)
Table WholesalerUser
CREATE TABLE [dbo].[WholesalerUser](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CustomerId] [int] NOT NULL,
[IsWholesaler] [bit] NOT NULL,
[UserId] [int] NOT NULL,
CONSTRAINT [PK_WholesalerUser] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
Foreign key
ALTER TABLE [dbo].[WholesalerUser] WITH CHECK
ADD CONSTRAINT [FK_WholesalerUser_Customer]
FOREIGN KEY([CustomerId], [IsWholesaler])
REFERENCES [dbo].[Customer] ([Id], [IsWholesaler])
GO
ALTER TABLE [dbo].[WholesalerUser]
CHECK CONSTRAINT [FK_WholesalerUser_Customer]
GO
Check constraint
ALTER TABLE [dbo].[WholesalerUser] WITH CHECK
ADD CONSTRAINT [CK_WholesalerUser]
CHECK (([IsWholesaler]=(1)))
GO
ALTER TABLE [dbo].[WholesalerUser]
CHECK CONSTRAINT [CK_WholesalerUser]
GO
ALTER TABLE [dbo].[WholesalerUser]
ADD CONSTRAINT [DF_WholesalerUser_IsWholesaler]
DEFAULT ((1)) FOR [IsWholesaler]
GO

Bulk inert to parent children tables

I have the following three tables (each RobotPart has exactly one arm and one leg). I have a large number of {arm, leg} pairs need to be inserted. Any new combinations of arm and leg will create a new entry in RobotPart. Any existing combination will not be inserted. No updates are needed for either parent or children. I need preserve the identity columns. Any efficient ways to accomplish this in SQL?
CREATE TABLE [dbo].[Arm](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Model] [varchar](20) NULL,
CONSTRAINT [PK_dbo.Arm] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
CREATE TABLE [dbo].[Leg](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Model] [varchar](10) NULL,
CONSTRAINT [PK_dbo.Leg] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
CREATE TABLE [dbo].[RobotPart](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](20) NOT NULL,
[ArmId] [int] NOT NULL,
[LegId] [int] NOT NULL,
CONSTRAINT [PK_dbo.RobotPart] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[RobotPart] WITH CHECK ADD CONSTRAINT [FK_dbo.RobotPart_dbo.Arm_ArmId] FOREIGN KEY([ArmId])
REFERENCES [dbo].[Arm] ([Id])
GO
ALTER TABLE [dbo].[RobotPart] WITH CHECK ADD CONSTRAINT [FK_dbo.RobotPart_dbo.Leg_LegId] FOREIGN KEY([LegId])
REFERENCES [dbo].[Leg] ([Id])
GO
Step 1: Insert new arms and legs using a LEFT OUTER JOINs from your source table to the arms and legs table, respectively. (a separate insert statement for each table)
Step 2: Insert the new combinations using an inner join from your source table to arms and legs and a left outer join from the your source table to the RobotPart table.
Here is my initial try on it using MERGE. Not sure how this compare to Lmu92 proposed.
CREATE TYPE [dbo].[RobotPart_udtt] AS TABLE(
[Arm] [varchar](20) NOT NULL,
[Leg] [varchar](10) NOT NULL,
[Name] [varchar](20) NOT NULL
)
GO
CREATE PROCEDURE dbo.[prc_Component_Create]
#robotParts [RobotPart_udtt] READONLY
AS
BEGIN
SET NOCOUNT ON;
DECLARE #messageId INT
DECLARE #status INT
MERGE [Arm] AS TARGET
USING (
SELECT
tR.arm AS Model
FROM #robotParts AS tR
) AS SOURCE
ON TARGET.Model = SOURCE.Model
WHEN NOT MATCHED THEN
INSERT
(
Model
)
VALUES
(
SOURCE.Model
);
MERGE [Leg] AS TARGET
USING (
SELECT
tR.leg AS Model
FROM #robotParts AS tR
) AS SOURCE
ON TARGET.Model = SOURCE.Model
WHEN NOT MATCHED THEN
INSERT
(
Model
)
VALUES
(
SOURCE.Model
);
WITH NewParts (ArmId, LegId, Name)
AS
(
SELECT tA.Id
, tL.Id
, tR.Name
FROM #robotParts AS tR
INNER JOIN [Arm] AS tA
ON tR.Arm = tA.Model
INNER JOIN [Leg] AS tL
ON tR.Leg = tL.Model
)
INSERT INTO RobotPart (Name, ArmId, LegId)
SELECT tN.Name
, tN.ArmId
, tN.LegId
FROM NewParts AS tN
LEFT JOIN RobotPart AS tR
ON tR.ArmId = tN.ArmId
AND tR.LegId = tN.LegId
WHERE tR.ArmId IS NULL AND tR.LegId IS NULL
END

Retrieve Data from Different Tables (SQL Server)

I have 4 tables in a SQL Server database with following schema:
Attendance
CREATE TABLE [dbo].[Attendance] (
[AttendanceId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[StudentId] UNIQUEIDENTIFIER NOT NULL,
[SubjectId] UNIQUEIDENTIFIER NOT NULL,
[Semester] INT NOT NULL,
[Month] NVARCHAR (50) NOT NULL,
[Count] INT NOT NULL,
CONSTRAINT [PK_Attendance] PRIMARY KEY NONCLUSTERED ([AttendanceId] ASC),
CONSTRAINT [FK_Attendance_Student] FOREIGN KEY ([StudentId]) REFERENCES [dbo].[Student] ([StudentId]) );
Course
CREATE TABLE [dbo].[Course] (
[CourseId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_Course] PRIMARY KEY NONCLUSTERED ([CourseId] ASC)
);
Student
CREATE TABLE [dbo].[Student] (
[StudentId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[RollNo] INT NOT NULL,
[Semester] INT NOT NULL,
CONSTRAINT [PK_Student] PRIMARY KEY NONCLUSTERED ([StudentId] ASC),
CONSTRAINT [FK_Student_Course] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId])
);
Subject
CREATE TABLE [dbo].[Subject] (
[SubjectId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[Semester] INT NOT NULL,
CONSTRAINT [PK_Subject] PRIMARY KEY NONCLUSTERED ([SubjectId] ASC),
CONSTRAINT [FK_Subject_Course] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId])
);
I need to create a attendance report in the following format:
Course Name | Student Name | Subject Name | Semester | Month | Count
Please tell me what SQL Query I need to use and if there's any change in schema required then suggest the same.
I'm looking forward to have your replies.
Thanks,
You need to use a JOIN in your query so that it only returns rows which match a [StudentId] from the Attendance table.
e.g.
SELECT c.CourseName, s.StudentName, u.SubjectName, u.Semester, a.Month, a.Count
FROM Student s
JOIN Attendance a ON s.StudentId = a.StudentId
JOIN Course c ON a.CourseId = c.CourseId
JOIN Subject u ON c.CourseId = u.CourseId
Something along these lines will only return rows which specifically match