Related
I have a database with parts that are stored in a table "Part". Each part undergoes a certain measurement (to determine its diameter) that is stored in the table "Measurement". The measurement uses a certain set of rules that are stored in a table "Ruleset". The rules are used to asses the part's category (it is possible that it matches multiple categories). So there is a cross table "Ruleset_x_Category" that's primary key is the combination of the foreign keys "ID_Ruleset" and "Category" to ensure that this combination is unique (each rule set can be combined with each category only ones) that is further connected the rule itself which than holds a Diameter_min- and Diameter_max-Value to check if the part matches the category. The number of rules per rule set varies.
The workflow: you have a part, you measure it, you pick a rule set for the measurement and then you are supposed to get a list that tells you if the part fit's in a number of categories.
Most of this is straight forward. Query for rules, get a "yes/no" if measurement is in between the min/max and so on. What is not easy to me is to get a new column for each row that I get if I query for the (variable number of) rules. Is this possible? And if so what is the technique that I use. Is there a better way to arrange my tables?
SELECT Measurement.id_part, Measurement.diameter, Category.Name, IIF(Measurement.diameter BETWEEN [Rule].Diameter_min AND [Rule].Diameter_max, 'Yes', 'No') As HitsCategory
FROM Measurement INNER JOIN
RuleSet ON Measurement.id_ruleset = RuleSet.ID INNER JOIN
RuleSet_x_Category ON RuleSet.ID = RuleSet_x_Category.Id_RuleSet INNER JOIN
[Rule] ON RuleSet_x_Category.id_rule = [Rule].Id INNER JOIN
Category ON RuleSet_x_Category.id_category = Category.Id
This get's me this:
What I want to have is this:
Larnu gave me the tip to use the pivot keyword. I found this article, however, I have trouble to apply it to my IIF statement. What I have tried:
DECLARE
#columns NVARCHAR(MAX) = '',
#sql NVARCHAR(MAX) = '';
-- select the category names
SELECT
#columns+=QUOTENAME([Name]) + ','
FROM
Category
ORDER BY
[Name];
-- remove the last comma
SET #columns = LEFT(#columns, LEN(#columns) - 1);
-- construct dynamic SQL
SET #sql ='
SELECT * FROM
(
SELECT Measurement.id, Measurement.id_part, Measurement.diameter, RuleSet.ID, Category.Name
FROM Measurement INNER JOIN
RuleSet ON Measurement.id_ruleset = RuleSet.ID INNER JOIN
RuleSet_x_Category ON RuleSet.ID = RuleSet_x_Category.Id_RuleSet INNER JOIN
[Rule] ON RuleSet_x_Category.id_rule = [Rule].Id INNER JOIN
Category ON RuleSet_x_Category.id_category = Category.Id
) t
PIVOT(
IIF(Measurement.diameter BETWEEN [Rule].Diameter_min AND [Rule].Diameter_max, ''true'', ''false'')
FOR [Name] IN ('+ #columns +')
) AS pivot_table;';
-- execute the dynamic SQL
EXECUTE sp_executesql #sql;
This gave me the Error:
Msg 195, Level 15, State 1, Line 12
'IIF' is not a recognized aggregate function.
Here is a script to create a demo data base I use to tinker with this problem:
USE [master]
GO
/****** Object: Database [Demo] Script Date: 6/10/2020 2:14:59 PM ******/
CREATE DATABASE [Demo]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'Demo', FILENAME = N'C:\Program Files\Demo.mdf' , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )
LOG ON
( NAME = N'Demo_log', FILENAME = N'C:\Program Files\Demo.ldf' , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )
GO
ALTER DATABASE [Demo] SET COMPATIBILITY_LEVEL = 140
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [Demo].[dbo].[sp_fulltext_database] #action = 'enable'
end
GO
ALTER DATABASE [Demo]SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [Demo]SET ANSI_NULLS OFF
GO
ALTER DATABASE [Demo]SET ANSI_PADDING OFF
GO
ALTER DATABASE [Demo]SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [Demo]SET ARITHABORT OFF
GO
ALTER DATABASE [Demo]SET AUTO_CLOSE OFF
GO
ALTER DATABASE [Demo]SET AUTO_SHRINK OFF
GO
ALTER DATABASE [Demo]SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [Demo]SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [Demo]SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [Demo]SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [Demo]SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [Demo]SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [Demo]SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [Demo]SET DISABLE_BROKER
GO
ALTER DATABASE [Demo]SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [Demo]SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [Demo]SET TRUSTWORTHY OFF
GO
ALTER DATABASE [Demo]SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [Demo]SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [Demo]SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [Demo]SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [Demo]SET RECOVERY FULL
GO
ALTER DATABASE [Demo]SET MULTI_USER
GO
ALTER DATABASE [Demo]SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [Demo]SET DB_CHAINING OFF
GO
ALTER DATABASE [Demo]SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO
ALTER DATABASE [Demo]SET TARGET_RECOVERY_TIME = 60 SECONDS
GO
ALTER DATABASE [Demo]SET DELAYED_DURABILITY = DISABLED
GO
EXEC sys.sp_db_vardecimal_storage_format N'DemoPivot', N'ON'
GO
ALTER DATABASE [Demo]SET QUERY_STORE = OFF
GO
USE [DemoPivot]
GO
/****** Object: Table [dbo].[Category] Script Date: 6/10/2020 2:14:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Category](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](70) NOT NULL,
CONSTRAINT [PK_Category] 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
/****** Object: Table [dbo].[Measurement] Script Date: 6/10/2020 2:14:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Measurement](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Id_Part] [int] NOT NULL,
[Id_RuleSet] [int] NOT NULL,
[Diameter] [float] NOT NULL,
CONSTRAINT [PK_Measurement] 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
/****** Object: Table [dbo].[Part] Script Date: 6/10/2020 2:14:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Part](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](70) NOT NULL,
CONSTRAINT [PK_Part] 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
/****** Object: Table [dbo].[Rule] Script Date: 6/10/2020 2:14:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Rule](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Diameter_min] [float] NOT NULL,
[Diameter_max] [float] NOT NULL,
CONSTRAINT [PK_Rule] 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
/****** Object: Table [dbo].[RuleSet] Script Date: 6/10/2020 2:14:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RuleSet](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_RuleSet] 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
/****** Object: Table [dbo].[RuleSet_x_Category] Script Date: 6/10/2020 2:14:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RuleSet_x_Category](
[Id_RuleSet] [int] NOT NULL,
[Id_Category] [int] NOT NULL,
[Id_Rule] [int] NOT NULL,
CONSTRAINT [PK_RuleSet_x_Category] PRIMARY KEY CLUSTERED
(
[Id_RuleSet] ASC,
[Id_Category] 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
SET IDENTITY_INSERT [dbo].[Category] ON
GO
INSERT [dbo].[Category] ([Id], [Name]) VALUES (1, N'A')
GO
INSERT [dbo].[Category] ([Id], [Name]) VALUES (2, N'B')
GO
INSERT [dbo].[Category] ([Id], [Name]) VALUES (3, N'C')
GO
INSERT [dbo].[Category] ([Id], [Name]) VALUES (4, N'D')
GO
INSERT [dbo].[Category] ([Id], [Name]) VALUES (5, N'E')
GO
INSERT [dbo].[Category] ([Id], [Name]) VALUES (6, N'F')
GO
INSERT [dbo].[Category] ([Id], [Name]) VALUES (7, N'G')
GO
SET IDENTITY_INSERT [dbo].[Category] OFF
GO
SET IDENTITY_INSERT [dbo].[Measurement] ON
GO
INSERT [dbo].[Measurement] ([Id], [Id_Part], [Id_RuleSet], [Diameter]) VALUES (1, 1, 1, 12)
GO
SET IDENTITY_INSERT [dbo].[Measurement] OFF
GO
SET IDENTITY_INSERT [dbo].[Part] ON
GO
INSERT [dbo].[Part] ([Id], [Name]) VALUES (1, N'myPart')
GO
SET IDENTITY_INSERT [dbo].[Part] OFF
GO
SET IDENTITY_INSERT [dbo].[Rule] ON
GO
INSERT [dbo].[Rule] ([Id], [Diameter_min], [Diameter_max]) VALUES (1, 10, 12)
GO
INSERT [dbo].[Rule] ([Id], [Diameter_min], [Diameter_max]) VALUES (2, 11, 13)
GO
INSERT [dbo].[Rule] ([Id], [Diameter_min], [Diameter_max]) VALUES (3, 12, 15)
GO
INSERT [dbo].[Rule] ([Id], [Diameter_min], [Diameter_max]) VALUES (4, 13, 18)
GO
INSERT [dbo].[Rule] ([Id], [Diameter_min], [Diameter_max]) VALUES (5, 13, 19)
GO
INSERT [dbo].[Rule] ([Id], [Diameter_min], [Diameter_max]) VALUES (6, 14, 16)
GO
INSERT [dbo].[Rule] ([Id], [Diameter_min], [Diameter_max]) VALUES (7, 15, 17)
GO
SET IDENTITY_INSERT [dbo].[Rule] OFF
GO
SET IDENTITY_INSERT [dbo].[RuleSet] ON
GO
INSERT [dbo].[RuleSet] ([Id], [Name]) VALUES (1, N'myRule')
GO
SET IDENTITY_INSERT [dbo].[RuleSet] OFF
GO
INSERT [dbo].[RuleSet_x_Category] ([Id_RuleSet], [Id_Category], [Id_Rule]) VALUES (1, 1, 1)
GO
INSERT [dbo].[RuleSet_x_Category] ([Id_RuleSet], [Id_Category], [Id_Rule]) VALUES (1, 2, 2)
GO
INSERT [dbo].[RuleSet_x_Category] ([Id_RuleSet], [Id_Category], [Id_Rule]) VALUES (1, 3, 3)
GO
INSERT [dbo].[RuleSet_x_Category] ([Id_RuleSet], [Id_Category], [Id_Rule]) VALUES (1, 4, 4)
GO
INSERT [dbo].[RuleSet_x_Category] ([Id_RuleSet], [Id_Category], [Id_Rule]) VALUES (1, 5, 5)
GO
INSERT [dbo].[RuleSet_x_Category] ([Id_RuleSet], [Id_Category], [Id_Rule]) VALUES (1, 6, 6)
GO
INSERT [dbo].[RuleSet_x_Category] ([Id_RuleSet], [Id_Category], [Id_Rule]) VALUES (1, 7, 7)
GO
ALTER TABLE [dbo].[Measurement] WITH CHECK ADD CONSTRAINT [FK_Measurement_Part] FOREIGN KEY([Id_Part])
REFERENCES [dbo].[Part] ([Id])
GO
ALTER TABLE [dbo].[Measurement] CHECK CONSTRAINT [FK_Measurement_Part]
GO
ALTER TABLE [dbo].[Measurement] WITH CHECK ADD CONSTRAINT [FK_Measurement_RuleSet] FOREIGN KEY([Id_RuleSet])
REFERENCES [dbo].[RuleSet] ([Id])
GO
ALTER TABLE [dbo].[Measurement] CHECK CONSTRAINT [FK_Measurement_RuleSet]
GO
ALTER TABLE [dbo].[RuleSet_x_Category] WITH CHECK ADD CONSTRAINT [FK_RuleSet_x_Category_Category] FOREIGN KEY([Id_Category])
REFERENCES [dbo].[Category] ([Id])
GO
ALTER TABLE [dbo].[RuleSet_x_Category] CHECK CONSTRAINT [FK_RuleSet_x_Category_Category]
GO
ALTER TABLE [dbo].[RuleSet_x_Category] WITH CHECK ADD CONSTRAINT [FK_RuleSet_x_Category_Rule] FOREIGN KEY([Id_Rule])
REFERENCES [dbo].[Rule] ([Id])
GO
ALTER TABLE [dbo].[RuleSet_x_Category] CHECK CONSTRAINT [FK_RuleSet_x_Category_Rule]
GO
ALTER TABLE [dbo].[RuleSet_x_Category] WITH CHECK ADD CONSTRAINT [FK_RuleSet_x_Category_RuleSet] FOREIGN KEY([Id_RuleSet])
REFERENCES [dbo].[RuleSet] ([Id])
GO
ALTER TABLE [dbo].[RuleSet_x_Category] CHECK CONSTRAINT [FK_RuleSet_x_Category_RuleSet]
GO
USE [master]
GO
ALTER DATABASE [Demo]SET READ_WRITE
GO
(background: I want to use this as a stored procedure from entity framework core in c# that is then the item source of a wpf (mvvm) data grid with a variable number of columns).
I could not get the values "yes"/"no" or "true"/"false" to be displayed because I could not work around the aggregate function that the PIVOT statement demands.
So I used a CASE statement that outputs 1 or 0, as Joel Coehoorn recommended.
This is my query:
DECLARE
#columns NVARCHAR(MAX) = '',
#sql NVARCHAR(MAX) = '';
-- select the category names
SELECT
#columns+=QUOTENAME([Name]) + ','
FROM
Category
ORDER BY
[Name];
-- remove the last comma
SET #columns = LEFT(#columns, LEN(#columns) - 1);
-- construct dynamic SQL
SET #sql ='
SELECT * FROM
(
SELECT Measurement.id_part, Category.Name,
Case
When Measurement.Diameter BETWEEN [RULE].Diameter_min AND [Rule].Diameter_max
THEN 1
Else
0
End As Hit
FROM Measurement INNER JOIN
RuleSet ON Measurement.id_ruleset = RuleSet.ID INNER JOIN
RuleSet_x_Category ON RuleSet.ID = RuleSet_x_Category.Id_RuleSet INNER JOIN
[Rule] ON RuleSet_x_Category.id_rule = [Rule].Id INNER JOIN
Category ON RuleSet_x_Category.id_category = Category.Id
) t
PIVOT(
sum(hit)
FOR [name] IN ('+ #columns +')
) AS pivot_table;';
-- execute the dynamic SQL
EXECUTE sp_executesql #sql;
And this is my result:
I have now three parts, each with a mesurement. If the diameter fits the rules criteria I get a 1, if not a zero. I can work with that.
I have now created a stored procedure that I can (hopefully) run from my app.
CREATE PROCEDURE GetCategories #idmesurement int
AS
DECLARE
#columns NVARCHAR(MAX) = '',
#sql NVARCHAR(MAX) = '';
-- select the category names
SELECT
#columns+=QUOTENAME([Name]) + ','
FROM
Category
ORDER BY
[Name];
-- remove the last comma
SET #columns = LEFT(#columns, LEN(#columns) - 1);
-- construct dynamic SQL
SET #sql ='
SELECT * FROM
(
SELECT Measurement.id_part, Category.Name,
Case
When Measurement.Diameter BETWEEN [RULE].Diameter_min AND [Rule].Diameter_max
THEN 1
Else
0
End As Hit
FROM Measurement INNER JOIN
RuleSet ON Measurement.id_ruleset = RuleSet.ID INNER JOIN
RuleSet_x_Category ON RuleSet.ID = RuleSet_x_Category.Id_RuleSet INNER JOIN
[Rule] ON RuleSet_x_Category.id_rule = [Rule].Id INNER JOIN
Category ON RuleSet_x_Category.id_category = Category.Id
WHERE Measurement.id = '+ CONVERT(varchar(10),#idmesurement) +'
) t
PIVOT(
sum(hit)
FOR [name] IN ('+ #columns +')
) AS pivot_table;';
-- execute the dynamic SQL
EXECUTE sp_executesql #sql;
With
GetCategories #idmesurement = 1
only outputs the result for my Measurement with the id=1.
Thanks a lot!
I have this table structure that store's employee's attendance daily. I want to get the result so that I could know under the date how many times employee marked attendance if it was checkin it'll give any status let's say IN and if it was checkout it'll say OUT in separate column.
/****** Object: Table [dbo].[Attendance] Script Date: 4/24/2019 2:22:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Attendance](
[EmpCode] [int] NULL,
[TimeIn] [datetime] NULL,
[TimeOut] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Employee] Script Date: 4/24/2019 2:22:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
[ID] [int] NOT NULL,
[EmployeeName] [varchar](25) NULL,
[Department] [varchar](25) NULL,
[CenterCode] [int] NULL,
CONSTRAINT [PK_Employee] 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
SET ANSI_PADDING OFF
GO
INSERT [dbo].[Attendance] ([EmpCode], [TimeIn], [TimeOut]) VALUES (1, CAST(N'2019-02-01 06:30:00.000' AS DateTime), NULL)
GO
INSERT [dbo].[Attendance] ([EmpCode], [TimeIn], [TimeOut]) VALUES (1, NULL, CAST(N'2019-02-01 18:22:00.000' AS DateTime))
GO
INSERT [dbo].[Attendance] ([EmpCode], [TimeIn], [TimeOut]) VALUES (1, CAST(N'2019-02-02 07:21:00.000' AS DateTime), NULL)
GO
INSERT [dbo].[Attendance] ([EmpCode], [TimeIn], [TimeOut]) VALUES (1, NULL, CAST(N'2019-02-02 19:54:00.000' AS DateTime))
GO
INSERT [dbo].[Employee] ([ID], [EmployeeName], [Department], [CenterCode]) VALUES (1, N'Asim', N'Information Tech', 4)
GO
INSERT [dbo].[Employee] ([ID], [EmployeeName], [Department], [CenterCode]) VALUES (2, N'Ali', N'Information Tech', 2)
GO
INSERT [dbo].[Employee] ([ID], [EmployeeName], [Department], [CenterCode]) VALUES (3, N'Isaac', N'Information Tech', 3)
GO
INSERT [dbo].[Employee] ([ID], [EmployeeName], [Department], [CenterCode]) VALUES (4, N'Swagger', N'Information Tech', 4)
GO
INSERT [dbo].[Employee] ([ID], [EmployeeName], [Department], [CenterCode]) VALUES (5, N'Nadine', N'Information Tech', 2)
GO
INSERT [dbo].[Employee] ([ID], [EmployeeName], [Department], [CenterCode]) VALUES (6, N'Julie', N'Information Tech', 4)
GO
INSERT [dbo].[Employee] ([ID], [EmployeeName], [Department], [CenterCode]) VALUES (7, N'Meachum', N'Information Tech', 3)
GO
INSERT [dbo].[Employee] ([ID], [EmployeeName], [Department], [CenterCode]) VALUES (8, N'Bob Lee', N'Information Tech', 4)
GO
ALTER TABLE [dbo].[Attendance] WITH CHECK ADD CONSTRAINT [FK_Attendance_Employee] FOREIGN KEY([EmpCode])
REFERENCES [dbo].[Employee] ([ID])
GO
ALTER TABLE [dbo].[Attendance] CHECK CONSTRAINT [FK_Attendance_Employee]
GO
Now I have wrote a query but as I'm not sure how to use PIVOT function without aggregate funciton so I'm using MIN() and that's why it's only giving me the first timein/timeout of the day.
Here is the query:
SELECT * FROM (
SELECT E.ID, E.EmployeeName, T.DateToCheck, COALESCE(A.val, 'Absent') val
FROM Employee E
CROSS JOIN (
SELECT CAST(DATEADD(DAY, number, '2019-02-01') AS DATE)
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(DAY, number, '2019-02-01') <= '2019-02-28') T(DateToCheck)
LEFT JOIN (SELECT CAST(CAST(COALESCE(TimeIn, TimeOut) AS TIME) AS VARCHAR) val, CAST(COALESCE(TimeIn, TimeOut) AS DATE) AttendanceDateTime, EmpCode FROM Attendance) A ON CAST(A.AttendanceDateTime AS DATE) = T.DateToCheck AND A.EmpCode = E.ID
) T
PIVOT (MIN(val) FOR DateToCheck IN ([2019-02-01],[2019-02-02],[2019-02-03],[2019-02-04],[2019-02-05],[2019-02-06],[2019-02-07],[2019-02-08],[2019-02-09],[2019-02-10],[2019-02-11],[2019-02-12],[2019-02-13],[2019-02-14],[2019-02-15],[2019-02-16],[2019-02-17],[2019-02-18],[2019-02-19],[2019-02-20],[2019-02-21],[2019-02-22],[2019-02-23],[2019-02-24],[2019-02-25],[2019-02-26],[2019-02-27],[2019-02-28])) P;
The expected output result is something like this
EmployeeName Status 2019-02-01 2019-02-02
Asim IN 06:30 07:21
Asim OUT 11:39 19:54
Asim IN 13:06 NULL
Asim OUT 18:22 NULL
i have an application serve multilevel of permissions and roles
i have this HIERARCHY :
Country
....Region
........City
............Association
................Center
....................School
........................Class
this HIERARCHY i name it "EntityLevels"
| ID | Name | ParentID |
|----|-------------|----------|
| 1 | Country | Null |
| 2 | Region | 1 |
| 3 | City | 2 |
| 4 | Association | 3 |
| 5 | Center | 4 |
| 6 | School | 5 |
| 7 | Class | 6 |
i have also a Groups Table which means Jobs
| ID | Name | EntityLevels |
|----|--------------------|--------------|
| 1 | CountryAdmins | 1 |
| 2 | Region Supervisors | 2 |
the user table is as following
| ID | Name |
|----|-------|
| 1 | User1 |
| 2 | User2 |
now i have a UserJobs Table or UserGroups
| ID | UserID | GroupdID | EntityID |
|----|--------|----------|----------|
| 1 | User1 | 1 | 1 |
| 2 | User2 | 2 | 2 |
| 3 | User3 | 4 | 38 |
now the problem is how i can get each user and his responsibilites depending on what it's under his level
for eaxmple :
user1 must have all the roles and permissoins to see all users under his level because he is in Group (1) and Group1 it resides on EntityLevel (1) which it's on the Country Level.
i've try to do something like that, but it's not working as Expected it's Only give me the root without any other child under that root
;WITH MyCTE AS (
SELECT T1.ID, UserId, 0 AS TreeLevel, CAST(T1.ID AS VARCHAR(255)) AS TreePath FROM UserJobs T1
inner join EntityLevel el on t1.GroupId = el.Id WHERE EL.ParentID IS NULL
UNION ALL
SELECT T2.ID, T2.UserId, TreeLevel + 1, CAST(TreePath + '.' + CAST(T2.ID AS VARCHAR(255)) AS VARCHAR(255)) AS TreePath
FROM UserJobs T2
inner join EntityLevel el on T2.GroupId = el.Id
INNER JOIN
MyCTE itms ON itms.ID = EL.ParentID
)
SELECT ID, TreeLevel, TreePath
FROM MyCTE
ORDER BY TreePath;
Script for Schema And DATA
dbfiddle here
CREATE TABLE [dbo].[Assocation](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CityID] [int] NULL,
CONSTRAINT [PK_Assocation] 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
/****** Object: Table [dbo].[Center] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Center](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[AssociationID] [int] NULL,
CONSTRAINT [PK_Center] 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
/****** Object: Table [dbo].[City] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[City](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[RegionID] [int] NULL,
CONSTRAINT [PK_City] 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
/****** Object: Table [dbo].[Class] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Class](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[SchoolID] [int] NULL,
CONSTRAINT [PK_Class] 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
/****** Object: Table [dbo].[Country] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Country](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Country] 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
/****** Object: Table [dbo].[EntityLevel] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EntityLevel](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[ParentID] [int] NULL,
CONSTRAINT [PK_Table_1] 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
/****** Object: Table [dbo].[Group] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Group](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[EntityLevelID] [int] NULL,
CONSTRAINT [PK_Group] 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
/****** Object: Table [dbo].[Region] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Region](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CountryID] [int] NULL,
CONSTRAINT [PK_Region] 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
/****** Object: Table [dbo].[School] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[School](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CenterID] [int] NULL,
CONSTRAINT [PK_School] 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
/****** Object: Table [dbo].[User] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[Mobile] [varchar](50) NULL,
CONSTRAINT [PK_User] 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
/****** Object: Table [dbo].[UserJobs] Script Date: 2017-04-03 6:07:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserJobs](
[ID] [int] NOT NULL,
[UserID] [int] NOT NULL,
[GroupID] [int] NOT NULL,
[EntityID] [int] NOT NULL,
CONSTRAINT [PK_UserJobs] PRIMARY KEY CLUSTERED
(
[ID] ASC,
[UserID] ASC,
[GroupID] ASC,
[EntityID] 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
INSERT [dbo].[Assocation] ([ID], [Name], [CityID]) VALUES (1, N'KH', 1)
GO
INSERT [dbo].[Assocation] ([ID], [Name], [CityID]) VALUES (2, N'mkh_ass', 2)
GO
INSERT [dbo].[Center] ([ID], [Name], [AssociationID]) VALUES (1, N'NorthCenter', 1)
GO
INSERT [dbo].[Center] ([ID], [Name], [AssociationID]) VALUES (2, N'SouthCenter', 1)
GO
INSERT [dbo].[City] ([ID], [Name], [RegionID]) VALUES (1, N'Jeddah', 1)
GO
INSERT [dbo].[City] ([ID], [Name], [RegionID]) VALUES (2, N'MakkahCiry', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (1, N'Class1-Ahmed', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (2, N'Class2-omar', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (3, N'class3_khaled', 2)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (4, N'class4_fahd', 2)
GO
INSERT [dbo].[Country] ([ID], [Name]) VALUES (1, N'KSA')
GO
INSERT [dbo].[Country] ([ID], [Name]) VALUES (2, N'UAE')
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (1, N'Country', NULL)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (2, N'Region', 1)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (3, N'City', 2)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (4, N'Association', 3)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (5, N'Center', 4)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (6, N'School', 5)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (7, N'Class', 6)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (1, N'SA', 1)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (2, N'country admin', 1)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (3, N'region admin', 2)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (4, N'region Supervisor', 2)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (5, N'manager', 4)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (6, N'supervisor', 5)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (7, N'teacher', 7)
GO
INSERT [dbo].[Region] ([ID], [Name], [CountryID]) VALUES (1, N'Makkah', 1)
GO
INSERT [dbo].[Region] ([ID], [Name], [CountryID]) VALUES (2, N'Riyadh', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (1, N'School1', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (2, N'School2', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (3, N'School3', 2)
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (1, N'Loai', N'000000')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (2, N'User1', N'1111')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (3, N'User2', N'2222')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (4, N'User3', N'3333')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (5, N'User4', N'4444')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (6, N'user5', N'5555')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (7, N'user6', N'6548')
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (1, 1, 1, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (2, 2, 2, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (3, 3, 3, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (4, 4, 4, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (5, 5, 5, 2)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (6, 6, 6, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (7, 7, 7, 2)
GO
(EDIT) : The Expected Result will be :
SCRIPT AND DATA VERSION #2
CREATE TABLE [dbo].[Assocation](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CityID] [int] NULL,
CONSTRAINT [PK_Assocation] 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
/****** Object: Table [dbo].[Center] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Center](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[AssociationID] [int] NULL,
CONSTRAINT [PK_Center] 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
/****** Object: Table [dbo].[City] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[City](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[RegionID] [int] NULL,
CONSTRAINT [PK_City] 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
/****** Object: Table [dbo].[Class] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Class](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[SchoolID] [int] NULL,
CONSTRAINT [PK_Class] 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
/****** Object: Table [dbo].[Country] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Country](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Country] 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
/****** Object: Table [dbo].[EntityLevel] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EntityLevel](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[ParentID] [int] NULL,
CONSTRAINT [PK_Table_1] 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
/****** Object: Table [dbo].[Group] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Group](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[EntityLevelID] [int] NULL,
CONSTRAINT [PK_Group] 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
/****** Object: Table [dbo].[Region] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Region](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CountryID] [int] NULL,
CONSTRAINT [PK_Region] 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
/****** Object: Table [dbo].[School] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[School](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CenterID] [int] NULL,
CONSTRAINT [PK_School] 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
/****** Object: Table [dbo].[User] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[Mobile] [varchar](50) NULL,
CONSTRAINT [PK_User] 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
/****** Object: Table [dbo].[UserJobs] Script Date: 2017-04-04 3:47:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserJobs](
[ID] [int] NOT NULL,
[UserID] [int] NOT NULL,
[GroupID] [int] NOT NULL,
[EntityID] [int] NOT NULL,
CONSTRAINT [PK_UserJobs] PRIMARY KEY CLUSTERED
(
[ID] ASC,
[UserID] ASC,
[GroupID] ASC,
[EntityID] 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
INSERT [dbo].[Assocation] ([ID], [Name], [CityID]) VALUES (1, N'KH', 1)
GO
INSERT [dbo].[Assocation] ([ID], [Name], [CityID]) VALUES (2, N'mkh_ass', 2)
GO
INSERT [dbo].[Center] ([ID], [Name], [AssociationID]) VALUES (1, N'NorthCenter', 1)
GO
INSERT [dbo].[Center] ([ID], [Name], [AssociationID]) VALUES (2, N'SouthCenter', 1)
GO
INSERT [dbo].[City] ([ID], [Name], [RegionID]) VALUES (1, N'Jeddah', 1)
GO
INSERT [dbo].[City] ([ID], [Name], [RegionID]) VALUES (2, N'MakkahCiry', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (1, N'Class1', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (2, N'Class2', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (3, N'class3', 2)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (4, N'class4', 2)
GO
INSERT [dbo].[Country] ([ID], [Name]) VALUES (1, N'KSA')
GO
INSERT [dbo].[Country] ([ID], [Name]) VALUES (2, N'UAE')
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (1, N'Country', NULL)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (2, N'Region', 1)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (3, N'City', 2)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (4, N'Association', 3)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (5, N'Center', 4)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (6, N'School', 5)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (7, N'Class', 6)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (1, N'Country Manager', 1)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (2, N'Region Manager', 2)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (3, N'City Manager', 3)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (4, N'Association Manager', 4)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (5, N'Center Manager', 5)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (6, N'School Manager', 6)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (7, N'Teacher', 7)
GO
INSERT [dbo].[Region] ([ID], [Name], [CountryID]) VALUES (1, N'Makkah', 1)
GO
INSERT [dbo].[Region] ([ID], [Name], [CountryID]) VALUES (2, N'Riyadh', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (1, N'School1', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (2, N'School2', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (3, N'School3', 2)
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (1, N'UserA', N'000000')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (2, N'UserB', N'1111')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (3, N'UserC', N'2222')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (4, N'UserD', N'3333')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (5, N'UserE', N'4444')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (6, N'UserF', N'5555')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (7, N'UserG', N'6548')
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (8, N'UserH', NULL)
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (9, N'UserI', NULL)
GO
INSERT [dbo].[User] ([ID], [Name], [Mobile]) VALUES (10, N'UserJ', NULL)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (1, 1, 1, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (2, 2, 2, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (3, 3, 3, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (4, 4, 4, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (5, 5, 5, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (6, 6, 6, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (7, 7, 7, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (8, 8, 2, 2)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (9, 9, 3, 2)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (10, 10, 4, 2)
GO
any solution for that ?
IMHO you must build the whole Entities tree and then use it to JOIN with the other tables.
Having a look at your desired result it is not clear to me what is the relation between Entities and Cities, Regions, Class, etc.
Obviously according to the Name of the entity, I know that 1 = Country, 2 = Region and so on, but I can't find out any field on your table schema that allow to get this information other than:
CASE WHEN Entity.ID = 1 (SELECT Name FROM Country WHERE ID = Entity.ID) END
WHEN Entity.ID = 2 (SELECT Name FROM Region WHERE ID = Entity.ID) END
WHEN Entity.ID = 3 (SELECT Name FROM City WHERE ID = Entity.ID) END
...
END as EntityName
I'd suggest you to build a UDF or SP to get the name of the Entity and use it on the next script.
;WITH tree AS
(
SELECT e1.ID, e1.Name, e1.ParentID, [level] = 1
FROM EntityLevel e1
WHERE e1.ParentID = (SELECT EntityID FROM UserJobs WHERE UserID = 1)
UNION ALL
SELECT e2.ID, e2.Name, e2.ParentID, [level] = tree.[level] + 1
FROM EntityLevel e2
INNER JOIN tree
ON e2.ParentID = tree.ID
)
SELECT EntityLevelID, UserName, GroupID, GroupName, EntityID, EntityName
FROM tree t
INNER JOIN (SELECT gr.entitylevelid,
us.Name UserName,
gr.Name GroupName,
el.Name as EntityName,
gr.ID as GroupID,
el.ID as EntityID
FROM userjobs uj
INNER JOIN [group] gr
ON gr.id = uj.groupid
INNER JOIN entitylevel el
ON el.id = gr.entitylevelid
INNER JOIN [user] us
ON us.id = uj.userid) t1
ON t.ID = t1.EntityLevelID
OPTION (MAXRECURSION 0)
;
GO
EntityLevelID | UserName | GroupID | GroupName | EntityID | EntityName
------------: | :------- | ------: | :---------------- | -------: | :----------
2 | User2 | 3 | region admin | 2 | Region
2 | User3 | 4 | region Supervisor | 2 | Region
4 | User4 | 5 | manager | 4 | Association
5 | user5 | 6 | supervisor | 5 | Center
7 | user6 | 7 | teacher | 7 | Class
dbfiddle here
Can you try this? (edited after comments)
;WITH MyCTE AS (
SELECT T1.ID, UserId, NULL AS PARENT_ID, T1.GroupID, G.EntityLevelID
FROM UserJobs T1
INNER JOIN [GROUP] G ON T1.GROUPID = G.ID
inner join EntityLevel el on G.EntityLevelID = el.Id
WHERE T1.UserID = 1 /* Write here the user id you want */
UNION ALL
SELECT T2.ID, T2.UserId, EL.ParentID, T2.GroupID, G.EntityLevelID
FROM UserJobs T2
INNER JOIN [GROUP] G ON T2.GROUPID = G.ID
inner join EntityLevel el on G.EntityLevelID = el.Id
INNER JOIN MyCTE itms ON EL.ParentID >= itms.ID
)
SELECT B.*, C.*, A.*
FROM (SELECT DISTINCT * FROM MyCTE) A
INNER JOIN [USER] B ON A.UserID = B.ID
INNER JOIN [Group] C ON A.GroupID = C.ID
;
Output:
ID Name Mobile ID Name EntityLevelID ID UserId PARENT_ID GroupID EntityLevelID
1 1 Loai 000000 1 SA 1 1 1 NULL 1 1
2 3 User2 2222 3 region admin 2 3 3 1 3 2
3 4 User3 3333 4 region Supervisor 2 4 4 1 4 2
4 5 User4 4444 5 manager 4 5 5 3 5 4
5 6 user5 5555 6 supervisor 5 6 6 4 6 5
6 7 user6 6548 7 teacher 7 7 7 6 7 7
I've this Tree
Country
Region
City
Association
Center
School
Class
i have this Query here
;WITH MyCTE AS
(
SELECT T1.ID, UserId, NULL AS PARENT_ID, T1.GroupID, G.EntityLevelID
FROM UserJobs T1
INNER JOIN [GROUP] G ON T1.GROUPID = G.ID
inner join EntityLevel el on G.EntityLevelID = el.Id
WHERE T1.UserID = 1
UNION ALL
SELECT T2.ID, T2.UserId, EL.ParentID, T2.GroupID, G.EntityLevelID
FROM UserJobs T2
INNER JOIN [GROUP] G ON T2.GROUPID = G.ID
inner join EntityLevel el on G.EntityLevelID = el.Id
INNER JOIN MyCTE itms ON EL.ParentID >= itms.ID
)
SELECT B.*, C.*, A.*
FROM (SELECT DISTINCT * FROM MyCTE) A
INNER JOIN [USER] B ON A.UserID = B.ID
INNER JOIN [Group] C ON A.GroupID = C.ID
order by a.GroupID ;
if i run this query for userID = 1
it will gives me correct Data (it will bring all the users that are under UserA = UserID = 1)
1 UserA 1 Country Manager 1 1 1 NULL 1 1
2 UserB 2 Region Manager 2 2 2 1 2 2
8 UserH 2 Region Manager 2 8 8 1 2 2
3 UserC 3 City Manager 3 3 3 2 3 3
9 UserI 3 City Manager 3 9 9 2 3 3
4 UserD 4 Association Manager 4 4 4 3 4 4
10 UserJ 4 Association Manager 4 10 10 3 4 4
5 UserE 5 Center Manager 5 5 5 4 5 5
6 UserF 6 School Manager 6 6 6 5 6 6
7 UserG 7 Teacher 7 7 7 6 7 7
this is actually what i looking for, but the problem comes when i need to get the user under UserI ID equal 9
The Result is :
9 UserI 3 City Manager 3 9 9 NULL 3 3
and that's wrong because UserI has one user Under him which is UserJ
so, the result must looks like
9 UserI 3 City Manager 3 9 9 NULL 3 3
10 UserJ 4 Association Manager 4 10 10 NULL 4 4
same error Occurs in UserID = 3 which gives me a UserJ which is out of tree
Script And Data is Here :
CREATE TABLE [dbo].[Assocation](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CityID] [int] NULL,
CONSTRAINT [PK_Assocation] 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
/****** Object: Table [dbo].[Center] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Center](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[AssociationID] [int] NULL,
CONSTRAINT [PK_Center] 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
/****** Object: Table [dbo].[City] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[City](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[RegionID] [int] NULL,
CONSTRAINT [PK_City] 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
/****** Object: Table [dbo].[Class] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Class](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[SchoolID] [int] NULL,
CONSTRAINT [PK_Class] 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
/****** Object: Table [dbo].[Country] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Country](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Country] 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
/****** Object: Table [dbo].[EntityLevel] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EntityLevel](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[ParentID] [int] NULL,
CONSTRAINT [PK_Table_1] 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
/****** Object: Table [dbo].[Group] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Group](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[EntityLevelID] [int] NULL,
CONSTRAINT [PK_Group] 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
/****** Object: Table [dbo].[Region] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Region](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CountryID] [int] NULL,
CONSTRAINT [PK_Region] 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
/****** Object: Table [dbo].[School] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[School](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[CenterID] [int] NULL,
CONSTRAINT [PK_School] 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
/****** Object: Table [dbo].[User] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_User] 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
/****** Object: Table [dbo].[UserJobs] Script Date: 2017-04-04 8:33:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserJobs](
[ID] [int] NOT NULL,
[UserID] [int] NOT NULL,
[GroupID] [int] NOT NULL,
[EntityID] [int] NOT NULL,
CONSTRAINT [PK_UserJobs] PRIMARY KEY CLUSTERED
(
[ID] ASC,
[UserID] ASC,
[GroupID] ASC,
[EntityID] 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
INSERT [dbo].[Assocation] ([ID], [Name], [CityID]) VALUES (1, N'KH', 1)
GO
INSERT [dbo].[Assocation] ([ID], [Name], [CityID]) VALUES (2, N'mkh_ass', 2)
GO
INSERT [dbo].[Center] ([ID], [Name], [AssociationID]) VALUES (1, N'NorthCenter', 1)
GO
INSERT [dbo].[Center] ([ID], [Name], [AssociationID]) VALUES (2, N'SouthCenter', 1)
GO
INSERT [dbo].[City] ([ID], [Name], [RegionID]) VALUES (1, N'Jeddah', 1)
GO
INSERT [dbo].[City] ([ID], [Name], [RegionID]) VALUES (2, N'MakkahCiry', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (1, N'Class1', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (2, N'Class2', 1)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (3, N'class3', 2)
GO
INSERT [dbo].[Class] ([ID], [Name], [SchoolID]) VALUES (4, N'class4', 2)
GO
INSERT [dbo].[Country] ([ID], [Name]) VALUES (1, N'KSA')
GO
INSERT [dbo].[Country] ([ID], [Name]) VALUES (2, N'UAE')
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (1, N'Country', NULL)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (2, N'Region', 1)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (3, N'City', 2)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (4, N'Association', 3)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (5, N'Center', 4)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (6, N'School', 5)
GO
INSERT [dbo].[EntityLevel] ([ID], [Name], [ParentID]) VALUES (7, N'Class', 6)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (1, N'Country Manager', 1)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (2, N'Region Manager', 2)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (3, N'City Manager', 3)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (4, N'Association Manager', 4)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (5, N'Center Manager', 5)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (6, N'School Manager', 6)
GO
INSERT [dbo].[Group] ([ID], [Name], [EntityLevelID]) VALUES (7, N'Teacher', 7)
GO
INSERT [dbo].[Region] ([ID], [Name], [CountryID]) VALUES (1, N'Makkah', 1)
GO
INSERT [dbo].[Region] ([ID], [Name], [CountryID]) VALUES (2, N'Riyadh', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (1, N'School1', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (2, N'School2', 1)
GO
INSERT [dbo].[School] ([ID], [Name], [CenterID]) VALUES (3, N'School3', 2)
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (1, N'UserA')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (2, N'UserB')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (3, N'UserC')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (4, N'UserD')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (5, N'UserE')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (6, N'UserF')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (7, N'UserG')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (8, N'UserH')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (9, N'UserI')
GO
INSERT [dbo].[User] ([ID], [Name]) VALUES (10, N'UserJ')
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (1, 1, 1, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (2, 2, 2, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (3, 3, 3, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (4, 4, 4, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (5, 5, 5, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (6, 6, 6, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (7, 7, 7, 1)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (8, 8, 2, 2)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (9, 9, 3, 2)
GO
INSERT [dbo].[UserJobs] ([ID], [UserID], [GroupID], [EntityID]) VALUES (10, 10, 4, 2)
GO
any solution for that ...
I will repeat that your PARENT_ID values are incorrect. Let us look in detail on the UserI (ID = 9) query to see why.
SELECT T1.ID, UserId, NULL AS PARENT_ID, T1.GroupID, G.EntityLevelID
FROM #UserJobs T1
INNER JOIN #GROUP G ON T1.GROUPID = G.ID
inner join #EntityLevel el on G.EntityLevelID = el.Id
WHERE T1.UserID = 9
This would be the base query when processing UserI, as defined in your data (NOTE: I used temp tables instead of permanent tables to simplify cleanup after the tests) The output of this query fragment looks like this:
ID UserId PARENT_ID GroupID EntityLevelID
9 9 NULL 3 3
No problem so far. So, the recursion portion of your CTE is:
UNION ALL
SELECT T2.ID, T2.UserId, EL.ParentID, T2.GroupID, G.EntityLevelID
FROM #UserJobs T2
INNER JOIN #GROUP G ON T2.GROUPID = G.ID
inner join #EntityLevel el on G.EntityLevelID = el.Id
INNER JOIN MyCTE itms
ON EL.ParentID >= itms.ID -- <<<< PROBLEM!!
As we see above, the value in itms.ID for the first part of this query is [9]. This needs to join to a value in the #EntityLevel.ParentID field. But if you look in the values you are inserting into the #EntityLevel table, your highest ParentID value is a [6]. Since there is no record matching the itms.ID value, no additional records are linked.
A similar problem comes with the UserID = 3 record (Examine the output of the queries to figure out why).
To recap - If you want an item to be linked to another item in a tree, there must be a specific, unique link between the items. You need to ensure that the specific, unique link exists. Note that it does not need to be a single data value, but every time your tree forks, the elements on one branch must be identifiably distinct from the elements on the other branch based on their data values.
I want to extract the result of a person in a poll by type of poll and a determined year, group by area.
This is the tables scripts and some sample data:
/****** Object: Table [dbo].[ANSWERS] Script Date: 09/09/2015 7:08:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ANSWERS](
[FK_QUESTION] [int] NOT NULL,
[CHOICE] [smallint] NOT NULL,
[TYPE_POLL] [bit] NOT NULL,
[FK_ID_PERSON] [decimal](18, 0) NOT NULL,
CONSTRAINT [PK_ANSWERS] PRIMARY KEY CLUSTERED
(
[FK_QUESTION] ASC,
[TYPE_POLL] ASC,
[FK_ID_PERSON] 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
/****** Object: Table [dbo].[AREA] Script Date: 09/09/2015 7:08:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AREA](
[ID_AREA] [int] IDENTITY(1,1) NOT NULL,
[FK_POLL] [int] NULL,
[NAME_AREA] [varchar](100) NULL,
CONSTRAINT [PK_AREA] PRIMARY KEY CLUSTERED
(
[ID_AREA] 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
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[JOBS] Script Date: 09/09/2015 7:08:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[JOBS](
[ID_JOB] [int] NOT NULL,
[NAME_JOB] [varchar](50) NOT NULL,
CONSTRAINT [PK_srh3100t] PRIMARY KEY CLUSTERED
(
[ID_JOB] 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
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[PERSON] Script Date: 09/09/2015 7:08:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PERSON](
[ID_PERSON] [decimal](18, 0) NOT NULL,
[JOB_PERSON] [int] NOT NULL,
[NAME] [varchar](200) NOT NULL,
[LAST_NAME] [varchar](200) NOT NULL,
CONSTRAINT [PK_PERSON] PRIMARY KEY CLUSTERED
(
[ID_PERSON] 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
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[POINTS] Script Date: 09/09/2015 7:08:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[POINTS](
[FK_JOB] [int] NOT NULL,
[FK_QUESTION] [int] NOT NULL,
[POINT] [numeric](4, 2) NOT NULL,
CONSTRAINT [PK_POINTS_1] PRIMARY KEY CLUSTERED
(
[FK_JOB] ASC,
[FK_QUESTION] 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
/****** Object: Table [dbo].[POLL] Script Date: 09/09/2015 7:08:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[POLL](
[ID_POLL] [int] IDENTITY(1,1) NOT NULL,
[YEARS] [smallint] NOT NULL,
[NAME] [varchar](100) NOT NULL,
[DATE_BEG] [date] NOT NULL,
[DATE_END] [date] NOT NULL,
[AUTO] [numeric](4, 2) NOT NULL,
[BOSS] [numeric](4, 2) NOT NULL,
CONSTRAINT [PK_POLL_1] PRIMARY KEY CLUSTERED
(
[ID_POLL] 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
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[QUESTION] Script Date: 09/09/2015 7:08:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[QUESTION](
[ID_QUESTION] [int] IDENTITY(1,1) NOT NULL,
[FK_AREA] [int] NULL,
[NAME] [varchar](50) NULL,
[DESCRIPTION] [varchar](400) NULL,
CONSTRAINT [PK_QUESTION] PRIMARY KEY CLUSTERED
(
[ID_QUESTION] 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
SET ANSI_PADDING OFF
GO
INSERT [dbo].[ANSWERS] ([FK_QUESTION], [CHOICE], [TYPE_POLL], [FK_ID_PERSON]) VALUES (1, 1, 0, CAST(1 AS Decimal(18, 0)))
INSERT [dbo].[ANSWERS] ([FK_QUESTION], [CHOICE], [TYPE_POLL], [FK_ID_PERSON]) VALUES (1, 1, 1, CAST(1 AS Decimal(18, 0)))
INSERT [dbo].[ANSWERS] ([FK_QUESTION], [CHOICE], [TYPE_POLL], [FK_ID_PERSON]) VALUES (2, 1, 0, CAST(1 AS Decimal(18, 0)))
INSERT [dbo].[ANSWERS] ([FK_QUESTION], [CHOICE], [TYPE_POLL], [FK_ID_PERSON]) VALUES (2, 2, 1, CAST(1 AS Decimal(18, 0)))
INSERT [dbo].[ANSWERS] ([FK_QUESTION], [CHOICE], [TYPE_POLL], [FK_ID_PERSON]) VALUES (3, 3, 0, CAST(1 AS Decimal(18, 0)))
INSERT [dbo].[ANSWERS] ([FK_QUESTION], [CHOICE], [TYPE_POLL], [FK_ID_PERSON]) VALUES (3, 1, 1, CAST(1 AS Decimal(18, 0)))
SET IDENTITY_INSERT [dbo].[AREA] ON
INSERT [dbo].[AREA] ([ID_AREA], [FK_POLL], [NAME_AREA]) VALUES (1, 1, N'AREA 1')
INSERT [dbo].[AREA] ([ID_AREA], [FK_POLL], [NAME_AREA]) VALUES (2, 1, N'AREA 2')
INSERT [dbo].[AREA] ([ID_AREA], [FK_POLL], [NAME_AREA]) VALUES (3, 1, N'AREA 3')
INSERT [dbo].[AREA] ([ID_AREA], [FK_POLL], [NAME_AREA]) VALUES (4, 1, N'AREA 4')
SET IDENTITY_INSERT [dbo].[AREA] OFF
INSERT [dbo].[JOBS] ([ID_JOB], [NAME_JOB]) VALUES (1, N'JOB 1')
INSERT [dbo].[JOBS] ([ID_JOB], [NAME_JOB]) VALUES (2, N'JOB 2')
INSERT [dbo].[JOBS] ([ID_JOB], [NAME_JOB]) VALUES (3, N'JOB 3')
INSERT [dbo].[JOBS] ([ID_JOB], [NAME_JOB]) VALUES (4, N'JOB 4')
INSERT [dbo].[PERSON] ([ID_PERSON], [JOB_PERSON], [NAME], [LAST_NAME]) VALUES (CAST(1 AS Decimal(18, 0)), 1, N'MATT', N'TUCK')
INSERT [dbo].[PERSON] ([ID_PERSON], [JOB_PERSON], [NAME], [LAST_NAME]) VALUES (CAST(2 AS Decimal(18, 0)), 2, N'MATT', N'HEAFY')
INSERT [dbo].[PERSON] ([ID_PERSON], [JOB_PERSON], [NAME], [LAST_NAME]) VALUES (CAST(3 AS Decimal(18, 0)), 3, N'SYNISTER', N'GATES')
INSERT [dbo].[PERSON] ([ID_PERSON], [JOB_PERSON], [NAME], [LAST_NAME]) VALUES (CAST(4 AS Decimal(18, 0)), 4, N'THOMAS', N'YOUNGBLOOD')
INSERT [dbo].[POINTS] ([FK_JOB], [FK_QUESTION], [POINT]) VALUES (1, 1, CAST(1.00 AS Numeric(4, 2)))
INSERT [dbo].[POINTS] ([FK_JOB], [FK_QUESTION], [POINT]) VALUES (1, 2, CAST(2.00 AS Numeric(4, 2)))
INSERT [dbo].[POINTS] ([FK_JOB], [FK_QUESTION], [POINT]) VALUES (1, 3, CAST(3.00 AS Numeric(4, 2)))
INSERT [dbo].[POINTS] ([FK_JOB], [FK_QUESTION], [POINT]) VALUES (1, 4, CAST(4.00 AS Numeric(4, 2)))
INSERT [dbo].[POINTS] ([FK_JOB], [FK_QUESTION], [POINT]) VALUES (2, 1, CAST(1.00 AS Numeric(4, 2)))
INSERT [dbo].[POINTS] ([FK_JOB], [FK_QUESTION], [POINT]) VALUES (2, 2, CAST(2.00 AS Numeric(4, 2)))
INSERT [dbo].[POINTS] ([FK_JOB], [FK_QUESTION], [POINT]) VALUES (2, 3, CAST(3.00 AS Numeric(4, 2)))
INSERT [dbo].[POINTS] ([FK_JOB], [FK_QUESTION], [POINT]) VALUES (2, 4, CAST(4.00 AS Numeric(4, 2)))
SET IDENTITY_INSERT [dbo].[POLL] ON
INSERT [dbo].[POLL] ([ID_POLL], [YEARS], [NAME], [DATE_BEG], [DATE_END], [AUTO], [BOSS]) VALUES (1, 2015, N'POLL 1', CAST(0x693A0B00 AS Date), CAST(0xD23A0B00 AS Date), CAST(20.00 AS Numeric(4, 2)), CAST(80.00 AS Numeric(4, 2)))
SET IDENTITY_INSERT [dbo].[POLL] OFF
SET IDENTITY_INSERT [dbo].[QUESTION] ON
INSERT [dbo].[QUESTION] ([ID_QUESTION], [FK_AREA], [NAME], [DESCRIPTION]) VALUES (1, 1, N'QUESTION 1', N'aaa')
INSERT [dbo].[QUESTION] ([ID_QUESTION], [FK_AREA], [NAME], [DESCRIPTION]) VALUES (2, 1, N'QUESTION 2', N'bbb')
INSERT [dbo].[QUESTION] ([ID_QUESTION], [FK_AREA], [NAME], [DESCRIPTION]) VALUES (3, 2, N'QUESTION 3', N'ccc')
INSERT [dbo].[QUESTION] ([ID_QUESTION], [FK_AREA], [NAME], [DESCRIPTION]) VALUES (4, 2, N'QUESTION 4', N'ddd')
INSERT [dbo].[QUESTION] ([ID_QUESTION], [FK_AREA], [NAME], [DESCRIPTION]) VALUES (5, 3, N'QUESTION 5', N'eee')
INSERT [dbo].[QUESTION] ([ID_QUESTION], [FK_AREA], [NAME], [DESCRIPTION]) VALUES (6, 3, N'QUESTION 6', N'fff')
INSERT [dbo].[QUESTION] ([ID_QUESTION], [FK_AREA], [NAME], [DESCRIPTION]) VALUES (7, 4, N'QUESTION 7', N'ggg')
INSERT [dbo].[QUESTION] ([ID_QUESTION], [FK_AREA], [NAME], [DESCRIPTION]) VALUES (8, 4, N'QUESTION 8', N'hhh')
SET IDENTITY_INSERT [dbo].[QUESTION] OFF
USE [master]
GO
And this is the query I have tried:
SELECT AREA.NAME_AREA,
(SELECT SUM(ANSWERS.CHOICE * POINTS.POINT / 5) WHERE ANSWERS.TYPE_POLL= 0) AS RESULT_PERSON,
(SELECT SUM(ANSWERS.CHOICE * POINTS.POINT / 5) WHERE ANSWERS.TYPE_POLL= 1) AS RESULT_BOSS
FROM POLL INNER JOIN
AREA ON POLL.ID_POLL = AREA.FK_POLL INNER JOIN
QUESTION ON AREA.ID_AREA = QUESTION.FK_AREA INNER JOIN
POINTS ON QUESTION.ID_QUESTION = POINTS.FK_QUESTION INNER JOIN
JOBS INNER JOIN
PERSON ON JOBS.ID_JOB = PERSON.JOB_PERSON ON POINTS.FK_JOB = JOBS.ID_JOB INNER JOIN
ANSWERS ON QUESTION.ID_QUESTION = ANSWERS.FK_QUESTION AND PERSON.ID_PERSON = ANSWERS.FK_ID_PERSON
WHERE (POLL.YEARS = 2015) AND (PERSON.ID_PERSON = 1) GROUP BY AREA.NAME_AREA , ANSWERS.TYPE_POLL
And I want the output be like this:
+------------+---------------+---------------+
| NAME_AREA | RESULT_PERSON | RESULT_BOSS |
+------------+---------------+---------------+
| AREA 1 | 0.6 | 1 |
| AREA 2 | 1.8 | 0.6 |
+------------+---------------+---------------+
But I'm getting the result like this:
+------------+---------------+---------------+
| NAME_AREA | RESULT_PERSON | RESULT_BOSS |
+------------+---------------+---------------+
| AREA 1 | 0.6 | NULL |
| AREA 2 | 1.8 | NULL |
| AREA 1 | NULL | 1 |
| AREA 2 | NULL | 0.6 |
+------------+---------------+---------------+
It is something I am missing...?
Without reading your query and finding better solution:
SELECT t.NAME_AREA, MAX(t.RESULT_PERSON) AS RESULT_PERSON, MAX(t.RESULT_BOSS) AS RESULT_BOSS
FROM (
SELECT AREA.NAME_AREA,
(SELECT SUM(ANSWERS.CHOICE * POINTS.POINT / 5) WHERE ANSWERS.TYPE_POLL= 0) AS RESULT_PERSON,
(SELECT SUM(ANSWERS.CHOICE * POINTS.POINT / 5) WHERE ANSWERS.TYPE_POLL= 1) AS RESULT_BOSS
FROM POLL INNER JOIN
AREA ON POLL.ID_POLL = AREA.FK_POLL INNER JOIN
QUESTION ON AREA.ID_AREA = QUESTION.FK_AREA INNER JOIN
POINTS ON QUESTION.ID_QUESTION = POINTS.FK_QUESTION INNER JOIN
JOBS INNER JOIN
PERSON ON JOBS.ID_JOB = PERSON.JOB_PERSON ON POINTS.FK_JOB = JOBS.ID_JOB INNER JOIN
ANSWERS ON QUESTION.ID_QUESTION = ANSWERS.FK_QUESTION AND PERSON.ID_PERSON = ANSWERS.FK_ID_PERSON
WHERE (POLL.YEARS = 2015) AND (PERSON.ID_PERSON = 1) GROUP BY AREA.NAME_AREA , ANSWERS.TYPE_POLL)
AS t
GROUP BY NAME_AREA;
I am aware there are more efficient and secure ways, this is just quick workaround.
You can pass It to subquery and add only NAME_AREA to GROUP BY clause in following:
SELECT NAME_AREA, MAX(RESULT_PERSON) AS RESULT_PERSON, MAX(RESULT_BOSS) AS RESULT_BOSS
FROM(
SELECT AREA.NAME_AREA,
(SELECT SUM(ANSWERS.CHOICE * POINTS.POINT / 5) WHERE ANSWERS.TYPE_POLL= 0) AS RESULT_PERSON,
(SELECT SUM(ANSWERS.CHOICE * POINTS.POINT / 5) WHERE ANSWERS.TYPE_POLL= 1) AS RESULT_BOSS
FROM POLL INNER JOIN
AREA ON POLL.ID_POLL = AREA.FK_POLL INNER JOIN
QUESTION ON AREA.ID_AREA = QUESTION.FK_AREA INNER JOIN
POINTS ON QUESTION.ID_QUESTION = POINTS.FK_QUESTION INNER JOIN
JOBS INNER JOIN
PERSON ON JOBS.ID_JOB = PERSON.JOB_PERSON ON POINTS.FK_JOB = JOBS.ID_JOB INNER JOIN
ANSWERS ON QUESTION.ID_QUESTION = ANSWERS.FK_QUESTION AND PERSON.ID_PERSON = ANSWERS.FK_ID_PERSON
WHERE (POLL.YEARS = 2015) AND (PERSON.ID_PERSON = 1)
GROUP BY AREA.NAME_AREA , ANSWERS.TYPE_POLL
)x
GROUP BY NAME_AREA
OUTPUT
NAME_AREA RESULT_PERSON RESULT_BOSS
AREA 1 0.600000 1.000000
AREA 2 1.800000 0.600000
Try this
SELECT AREA.NAME_AREA,
Sum(CASE WHEN ANSWERS.TYPE_POLL = 0 THEN ANSWERS.CHOICE * POINTS.POINT / 5 ELSE 0 END) AS RESULT_PERSON,
Sum(CASE WHEN ANSWERS.TYPE_POLL = 1 THEN ANSWERS.CHOICE * POINTS.POINT / 5 ELSE 0 END) AS RESULT_BOSS
FROM POLL
INNER JOIN AREA
ON POLL.ID_POLL = AREA.FK_POLL
INNER JOIN QUESTION
ON AREA.ID_AREA = QUESTION.FK_AREA
INNER JOIN POINTS
ON QUESTION.ID_QUESTION = POINTS.FK_QUESTION
INNER JOIN JOBS
ON POINTS.FK_JOB = JOBS.ID_JOB
INNER JOIN PERSON
ON JOBS.ID_JOB = PERSON.JOB_PERSON
INNER JOIN ANSWERS
ON QUESTION.ID_QUESTION = ANSWERS.FK_QUESTION
AND PERSON.ID_PERSON = ANSWERS.FK_ID_PERSON
WHERE ( POLL.YEARS = 2015 )
AND ( PERSON.ID_PERSON = 1 )
GROUP BY AREA.NAME_AREA