SQL tree data rebuild - sql

Good morning,
I have an issue with a SQL query on hierarchic data.
I have to store the position of products on the shelfs in a supermarket.
Products can be moved but I have to maintain the history in order to produce sales statistics.
Records in the table are hierarchically linked and they can change some of their information and the position on the shelf.
Shelf_code: identify the shelf hierarchic position (i.e. aisle, shelf, level, sector…)
Shelf_position: details the location on shelf level.
parentId is set to null for the first insert occurrence of a record and is set to the ancestor record id for the further versions.
I’ve produced a tree structured set of records that can be shown like in the picture.
At the beginning of the year the products are positioned as follows
enter image description here
Then a new brand has been inserted between B and C and C has been moved in a different position (with his children C flavour x and C flavour y)
In the database new records are created for Brand C items with the new shelf code and position, parent id is now not null and corresponds to the id of the original record.
When I rebuild the supermarket shelfs tree, I want to show only the new positions
enter image description here
I tried to get data using partition over Shelf_position but I get twice the records named “Flowour x” and “Flowour y”: both in the correct position but also in the previous one (so they look like being Brand New sons that isn’t correct)
enter image description here
My query:
SELECT Shelfs.*
FROM Shelfs
WHERE Shelfs.ID IN(
SELECT id
FROM
(SELECT m.*, ROW_NUMBER() over
(partition by Shelf_Position order by m.time_stamp desc) as rn
FROM Shelfs m) m2
WHERE m2.rn = 1)
ORDER BY Shelf_Code, Shelf_Position
To get item genealogy of product named “Flavour x” I’ve used the query listed below.
Selecting the most recent item I can get the last one
WITH Anchestors AS (
SELECT Shelfs.*
,0 AS lv
FROM Shelfs
WHERE id = #productId
UNION ALL
SELECT parent.*
, lv+1 as lv
FROM Shelfs parent
INNER JOIN Anchestors a
ON parent.id = a.parentId
)
SELECT #rootId = ( SELECT top(1) id
FROM Anchestors
order by lv desc);
-- select root descendants
WITH generation AS (
SELECT Shelfs.*
,0 AS lv
FROM Shelfs
WHERE parentId IS NULL
and id = #rootId
UNION ALL
SELECT child.*
, lv+1 as lv
FROM Shelfs child
INNER JOIN generation g
ON g.id = child.parentId
)
SELECT *
FROM generation
order by lv
But this query is parametrized for a specific product and I wasn’t able to generalize it in order to get the last version of all the items.
Can anyone help me to find out the correct way to get the data?
Thanks in advance to everybody.
Database table script:
CREATE TABLE [dbo].[Shelfs](
[id] [uniqueidentifier] NOT NULL,
[Name] [nchar](10) NULL,
[Shelf_Code] [nvarchar](max) NULL,
[Shelf_Position] [nvarchar](max) NULL,
[parentId] [uniqueidentifier] NULL,
[time_stamp] [datetime] NULL,
CONSTRAINT [PK_Shelfs] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Shelfs] ADD CONSTRAINT [DF_Shelfs_id] DEFAULT (newid()) FOR [id]
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'043be568-8cc6-4624-9373-64d31a032745', N'Level 1 ', N'0101', N'010101', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'27ccf84c-5a08-425b-a355-6fb1f99eda3a', N'Flavour x ', N'0101010103', N'010101010301', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'9e841e78-571a-4009-8d40-81fc9045b99e', N'Brand C ', N'01010101', N'0101010104', N'37035b46-6a1a-47b6-8bdc-4a6ecfd68b9e', CAST(N'2022-02-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'da5119e1-c327-463a-b8e9-84453a1495cc', N'2nd Aisle ', N'00', N'02', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'b3e67cd1-c726-4bcf-a30c-9b7945a2ea9f', N'Left ', N'01', N'0101', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'08c2d2bb-0980-4d0d-899d-a4d23c0c7878', N'Flavour x ', N'0101010104', N'010101010401', N'27ccf84c-5a08-425b-a355-6fb1f99eda3a', CAST(N'2022-02-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'56825bd1-55ab-4c65-86c0-aff40550b785', N'Flavour y ', N'0101010103', N'010101010302', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'4a8e4ef7-926c-4eca-a520-b580f7035f44', N'Right ', N'01', N'0102', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'c53d35bc-f31b-4a67-a9e7-b82fbae5f7dc', N'Sector 1 ', N'010101', N'01010101', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'c70a6b81-8967-4ae8-a16c-bc6a925e1f61', N'Flavour y ', N'0101010104', N'010101010402', N'56825bd1-55ab-4c65-86c0-aff40550b785', CAST(N'2022-02-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'c46948f0-2d5e-48cf-a773-dcc44a434779', N'Brand B ', N'01010101', N'0101010102', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))
INSERT [dbo].[Shelfs] ([id], [Name], [Shelf_Code], [Shelf_Position], [parentId], [time_stamp]) VALUES (N'63123c3e-36bf-477e-919b-f245f0ff80c2', N'Sector 2 ', N'010101', N'01010102', NULL, CAST(N'2022-01-01T08:00:00.000' AS DateTime))

I fancy I've found the solution for my issue.
For who has interest in it, here's the query:
WITH ShelfsTree([id]
,[Name]
,[Shelf_Code]
,[Shelf_Position]
,[parentId]
,[Time_stamp]
, lv)
AS (SELECT a.[id],
a.[Name],
a.[Shelf_Code],
a.[Shelf_Position],
a.[parentId] Parent,
a.[Time_stamp],
0 AS lv
FROM Shelfs a
WHERE a.[parentId] IS NULL
AND a.[parentId] IS NULL
UNION ALL
SELECT a2.[id],
a2.[Name],
a2.[Shelf_Code],
a2.[Shelf_Position],
a2.[parentId] Parent,
a2.[Time_stamp],
ShelfsTree.lv + 1 lv
FROM Shelfs a2
INNER JOIN ShelfsTree ON ShelfsTree.[id] = a2.[parentId]
WHERE a2.[parentId] IS NOT NULL
)
select *
from ShelfsTree
where id not in (select [parentId] from Shelfs where [parentId] is not null)
order by Shelf_Code, Shelf_Position, Time_stamp desc
Thanks.

Related

MS SQL Server 2008 query - doesn't get proper send and received message count

SELECT DISTINCT
U.UserId as 'Id',
U.FullName as 'Name',
(SELECT COUNT(*) FROM [Conversation]
WHERE FromUserId = 'user1' AND ToUserId = U.UserId) 'SentCount',
(SELECT COUNT(*) FROM [Conversation]
WHERE ToUserId = 'user1' AND FromUserId = U.UserId) 'ReceivedCount'
FROM
[Conversation] C
INNER JOIN
[User] U ON U.UserId = C.FromUserId
WHERE
C.ToUserId = 'user1'
Query returns a result but it doesn't include some of the rows. Conversation table contains the same FromUserId (send message user) and ToUserId (receive message user).
Here are the tables :
Current result -
Expected result:
Table with dummy data -
CREATE TABLE [dbo].[User](
[Id] [int] NULL,
[UserId] [varchar](5) NULL,
[Name] [varchar](5) NULL,
[Email] [varchar](11) NULL
) ON [PRIMARY]
INSERT [dbo].[User] ([Id], [UserId], [Name], [Email]) VALUES (1, N'user1', N'user1', N'user1#a.com')
INSERT [dbo].[User] ([Id], [UserId], [Name], [Email]) VALUES (2, N'user2', N'user2', N'user2#a.com')
INSERT [dbo].[User] ([Id], [UserId], [Name], [Email]) VALUES (3, N'user3', N'user3', N'user3#a.com')
INSERT [dbo].[User] ([Id], [UserId], [Name], [Email]) VALUES (4, N'user4', N'user4', N'user4#a.com')
INSERT [dbo].[User] ([Id], [UserId], [Name], [Email]) VALUES (5, N'user5', N'user5', N'user5#a.com')
CREATE TABLE [dbo].[Conversation](
[Id] [int] NULL,
[conversationId] [varchar](14) NULL,
[messageId] [varchar](4) NULL,
[fromUserId] [varchar](5) NULL,
[toUserId] [varchar](5) NULL
) ON [PRIMARY]
INSERT [dbo].[Conversation] ([Id], [conversationId], [messageId], [fromUserId], [toUserId]) VALUES (1, N'con-user1user2', N'mes1', N'user1', N'user2')
INSERT [dbo].[Conversation] ([Id], [conversationId], [messageId], [fromUserId], [toUserId]) VALUES (2, N'con-user1user2', N'mes2', N'user1', N'user2')
INSERT [dbo].[Conversation] ([Id], [conversationId], [messageId], [fromUserId], [toUserId]) VALUES (3, N'con-user2user1', N'mes3', N'user2', N'user1')
INSERT [dbo].[Conversation] ([Id], [conversationId], [messageId], [fromUserId], [toUserId]) VALUES (4, N'con-user1user3', N'mes4', N'user1', N'user3')
INSERT [dbo].[Conversation] ([Id], [conversationId], [messageId], [fromUserId], [toUserId]) VALUES (5, N'con-user4user1', N'mes5', N'user4', N'user1')
Can someone help how to includes all the records?
Thanks!
You don't need a join in the outer query. This would be more simply written as:
SELECT U.UserId as Id, U.FullName as Name,
(SELECT COUNT(*)
FROM [Conversation] c
WHERE c.FromUserId = 'user1' AND c.ToUserId = U.UserId
) as SentCount,
(SELECT COUNT(*)
FROM [Conversation] c
WHERE c.ToUserId = 'user1' AND c.FromUserId = U.UserId
) as ReceivedCount
FROM [User] U ;
Notes:
Qualify all column references. This is particularly important for correlation clauses.
Give tables aliases that are abbreviations for the table names.
Only use single quotes for string and date constants. Do not use the for column aliases.
Here is a db<>fiddle.
You don't need the conversation table at your base select. Something like this would work, but can be optimised with subqueries:
Select U.UserId as 'Id',
U.name as 'Name',
isnull(fromSummed.sentCount, 0) 'SentCount',
isnull(ToSummed.ReceivedCount, 0) 'ReceivedCount'
FROM [User] U
outer apply (select count(*) as sentCount from [Conversation] cFrom where cFrom.FromUserId = 'user1' and ToUserId = U.UserId ) fromSummed
outer apply (select count(*) as ReceivedCount from [Conversation] cTo where cTo.ToUserId = 'user1' and cTo.FromUserId = U.UserId) ToSummed
where isnull(fromSummed.sentCount, 0)>0 or isnull(ToSummed.ReceivedCount, 0)>0

Get Nested JSON from SQL table

Below is my table data looks like.
Below is SQL Query for Create table
CREATE TABLE [dbo].[CategoryMaster](
[CategoryId] [int] NOT NULL,
[ParentId] [int] NULL,
[Name] [varchar](50) NULL,
CONSTRAINT [PK_CategoryMaster] PRIMARY KEY CLUSTERED
(
[CategoryId] 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].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (1, NULL, N'Toys & Games')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (2, 1, N'Art And Crafts')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (3, 1, N'Baby & Toddler Toys')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (4, 1, N'Bikes, Trikes & Ride-Ons')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (5, 2, N'Aprons & Smocks')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (6, 2, N'Blackboards & Whiteboards')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (7, 2, N'Clay & Dough')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (8, 1, N'Pretend Play')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (9, 8, N'Kitchen Toys')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (10, 9, N'Cooking Appliances')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (11, 9, N'Cookware')
GO
ALTER TABLE [dbo].[CategoryMaster] WITH CHECK ADD CONSTRAINT [FK_CategoryMaster_CategoryMaster] FOREIGN KEY([ParentId])
REFERENCES [dbo].[CategoryMaster] ([CategoryId])
GO
ALTER TABLE [dbo].[CategoryMaster] CHECK CONSTRAINT [FK_CategoryMaster_CategoryMaster]
GO
I had tried many queries but not able to get desired result. can anyone please help me out from this situation?
I want output like below.
You can create a recursive function like below:
CREATE FUNCTION Create_Json(#CategoryId INT, #IsRoot INT)
RETURNS VARCHAR(MAX)
BEGIN
DECLARE #Json NVARCHAR(MAX) = '{}', #Name NVARCHAR(MAX), #Children NVARCHAR(MAX)
SET #Json = (SELECT P.[Name],JSON_QUERY(dbo.Create_Json(P.CategoryId, 2) ) AS Children
FROM [dbo].[CategoryMaster] AS P
WHERE P.ParentId = #CategoryId
FOR JSON AUTO);
IF(#IsRoot = 1)
BEGIN
SELECT #Name = P.[Name] FROM [dbo].[CategoryMaster] AS P WHERE P.CategoryId = #CategoryId
SET #Json = '"result": {"Name":"' + #Name + '","Children":' + CAST(#Json AS NVARCHAR(MAX)) + '}'
SET #IsRoot = 0
END
RETURN #Json
END
and call it like:
select dbo.Create_Json(1, 1)
Please find the db<>fiddle here.

SQL Recursive Count

I have two tables I am joining with the following structure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ContentDivider](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ParentId] [int] NULL,
[Name] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_ContentDivider] 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].[CustomPage] Script Date: 23-03-2020 17:46:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CustomPage](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ContentDividerId] [int] NOT NULL,
[Name] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_CustomPage] 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
A ContentDivider can have n ContentDividers as Children and can have m CustomPages as children as well.
I want a View that counts the Display the current CustomDivider and the COunt for all the CustomPages as Children of the current ContentDivider.
My Test data:
SET IDENTITY_INSERT [dbo].[ContentDivider] ON
GO
INSERT [dbo].[ContentDivider] ([Id], [ParentId], [Name]) VALUES (1, NULL, N'TopLevel1')
INSERT [dbo].[ContentDivider] ([Id], [ParentId], [Name]) VALUES (2, NULL, N'TopLevel2')
INSERT [dbo].[ContentDivider] ([Id], [ParentId], [Name]) VALUES (3, NULL, N'TopLevel3')
INSERT [dbo].[ContentDivider] ([Id], [ParentId], [Name]) VALUES (4, 1, N'SecondLevel1')
INSERT [dbo].[ContentDivider] ([Id], [ParentId], [Name]) VALUES (5, 1, N'SecondLevel2')
INSERT [dbo].[ContentDivider] ([Id], [ParentId], [Name]) VALUES (6, 1, N'SecondLevel3')
INSERT [dbo].[ContentDivider] ([Id], [ParentId], [Name]) VALUES (7, 4, N'ThirdLevel1')
INSERT [dbo].[ContentDivider] ([Id], [ParentId], [Name]) VALUES (8, 4, N'ThirdLevel2')
GO
SET IDENTITY_INSERT [dbo].[ContentDivider] OFF
GO
SET IDENTITY_INSERT [dbo].[CustomPage] ON
GO
INSERT [dbo].[CustomPage] ([Id], [ContentDividerId], [Name]) VALUES (1, 1, N'Level1_1')
INSERT [dbo].[CustomPage] ([Id], [ContentDividerId], [Name]) VALUES (2, 1, N'Level1_2')
INSERT [dbo].[CustomPage] ([Id], [ContentDividerId], [Name]) VALUES (3, 2, N'Level1_3')
INSERT [dbo].[CustomPage] ([Id], [ContentDividerId], [Name]) VALUES (4, 2, N'Level1_4')
INSERT [dbo].[CustomPage] ([Id], [ContentDividerId], [Name]) VALUES (5, 4, N'Level1_5')
INSERT [dbo].[CustomPage] ([Id], [ContentDividerId], [Name]) VALUES (6, 5, N'Level1_6')
INSERT [dbo].[CustomPage] ([Id], [ContentDividerId], [Name]) VALUES (7, 7, N'Level1_7')
INSERT [dbo].[CustomPage] ([Id], [ContentDividerId], [Name]) VALUES (8, 8, N'Level1_8')
GO
SET IDENTITY_INSERT [dbo].[CustomPage] OFF
GO
And the View I want to extend:
SELECT dbo.ContentDivider.ParentId, dbo.ContentDivider.Name, dbo.ContentDivider.Id, COUNT(DISTINCT dbo.CustomPage.Id) AS CustomPageCount
FROM dbo.ContentDivider LEFT OUTER JOIN
dbo.CustomPage ON dbo.ContentDivider.Id = dbo.CustomPage.ContentDividerId
GROUP BY dbo.ContentDivider.ParentId, dbo.ContentDivider.Name, dbo.ContentDivider.Id
As for now the view counts the custompages directly underneath the contentdivider. I would like all the CustomPages as children counted.
Any suggestions?
The respected result would be:
View
this sounds like a perfect situation for recursive cte ;)
So, if I understood correctly, your expected result would be Toplevel1 with 6 pages and Toplevel 2 with 2 pages since all the other levels are somewhere beneath these two mentioned levels?
The cte might look something like this (maybe you habe to include the max recursion option):
WITH cte AS(
SELECT 1 lvl, ID AS ParentID, ID, Name
FROM dbo.ContentDivider cd
WHERE ParentId IS NULL
UNION ALL
SELECT c.lvl+1 AS lvl, c.ParentID, cd.ID, cd.Name
FROM dbo.ContentDivider cd
INNER JOIN cte c ON cd.ParentID = c.ID
)
SELECT c.ParentID, cd.Name, COUNT(DISTINCT cp.Id) AS CustomPageCount
FROM cte c
JOIN dbo.ContentDivider cd ON cd.ID = c.ParentID
LEFT OUTER JOIN dbo.CustomPage cp ON cp.ContentDividerId = c.id
GROUP BY c.ParentId, cd.Name
This leads to all pages being assigned to its top level.
See fiddle for details: http://sqlfiddle.com/#!18/f1a44/28/1
Edit: Since you need the details down to DividerID, I extended my example in the fiddle. First of all, I fetch the PageCount per ID in one cte and additionally the PageCount aggregated on level (ParentID and all its IDs) - this done you don't need the count and grouping in the following ctes.
In my query I then check, if my current rows ID is a top-level of any kind and assign the corresponding PageCount to this row.
WITH cteCnt AS(
SELECT cd.ID, COUNT(DISTINCT cp.Id) AS CustomPageCount
FROM dbo.ContentDivider cd
LEFT OUTER JOIN dbo.CustomPage cp ON cp.ContentDividerId = cd.id
GROUP BY cd.ID
),
cteTop AS(
SELECT cd.ID, COUNT(DISTINCT cp.Id) AS CustomPageCount
FROM dbo.ContentDivider cd
LEFT OUTER JOIN dbo.CustomPage cp ON cp.ContentDividerId = cd.id
GROUP BY cd.ID
UNION ALL
SELECT cd.ParentID, COUNT(DISTINCT cp.Id) AS CustomPageCount
FROM dbo.ContentDivider cd
LEFT OUTER JOIN dbo.CustomPage cp ON cp.ContentDividerId = cd.id
WHERE cd.ParentID IS NOT NULL
GROUP BY cd.ParentID
),
cteTopSum AS(
SELECT ID, SUM(CustomPageCount) AS CustomPageCount
FROM ctetop
GROUP BY ID
),
cte AS(
SELECT 1 lvl, cd.ID AS ParentID, cd.ID AS ParentIDx, cd.ID, cd.Name, cnt.CustomPageCount
FROM dbo.ContentDivider cd
INNER JOIN cteCnt cnt ON cnt.ID = cd.ID
WHERE ParentId IS NULL
UNION ALL
SELECT c.lvl+1 AS lvl, c.ParentID, cd.ParentID AS ParentIDx, cd.ID, cd.Name, cnt.CustomPageCount
FROM dbo.ContentDivider cd
INNER JOIN cteCnt cnt ON cnt.ID = cd.ID
INNER JOIN cte c ON cd.ParentID = c.ID
),
cteOut AS(
SELECT *
,SUM(CustomPageCount) OVER (PARTITION BY ParentID) x
,SUM(CustomPageCount) OVER (PARTITION BY ParentIDx) y
FROM cte c
)
SELECT CASE WHEN co.ParentIDx = co.ID THEN NULL ELSE co.ParentIDx END AS ParentID, co.ID, co.Name, CASE WHEN co.ID = co.ParentID THEN co.X ELSE ts.CustomPageCount END CustomPageCount
FROM cteOut co
LEFT JOIN cteTopSum ts ON ts.ID = co.ID
ORDER BY 1, 2
See new fiddle for details: http://sqlfiddle.com/#!18/f1a44/185/1
I'm mot sure, if there is a prettier / nicer way to solve this, but seemingly this seems to solve the problem.
However, I did NOT check if it works if any number of sublevels or whatsoever - if you find any issues, feel free to comment.

SQL Server CTE statement Varbinary(MAX) Not Returning the RootID

I have a hierarchy table to store a binary tree. I'm using a recursive query to retrieve the tree level based on the IntroducerID as the "RootID". The value returned as what I expected, but after the AgentId number increment reached 116, this CTE query doesn't return the Level value in hierarchical form.
Like it cannot trace the RootID anymore.
This is what my table structure looks like;
CREATE TABLE [dbo].[TblHierarchy]
(
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[AgentID] [bigint] NULL,
[AgentName] [varchar](50) NULL,
[RootID] [bigint] NULL,
[IntroducerID] [bigint] NULL,
[Description] [varchar](50) NULL,
[HierarchyTree] [hierarchyid] NULL
) ON [PRIMARY]
Below is the sample data from the table;
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (1, 1, N'Toh', 0, NULL, N'', NULL)
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (2, 2, N'Man', 1, 0, N'Child of Toh', NULL)
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (3, 3, N'Rul', 1, 0, N'Child of Toh', NULL)
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (4, 4, N'Rafiq', 2, 2, N'Child of Man', NULL)
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (5, 5, N'Paan', 2, 2, N'Child of Man', NULL)
And this is the query to retrieve the info.
WITH CTE AS
(
SELECT
H1.AgentID,
H1.RootID,
H1.AgentName,
H1.Description [Parent],
Description [Self Description],
CAST(AgentID AS varbinary(MAX)) [Level],
CAST (h1.AgentID AS varchar(max)) [LevelID],
CAST (H1.IntroducerID AS varchar(max)) [IntroducerID]
FROM
TblHierarchy H1
WHERE
H1.RootID = 3
UNION ALL
SELECT
H2.AgentID,
H2.RootID,
H2.AgentName,
c.[Self Description],
Description [Self Description],
c.[Level]+CAST(h2.AgentID AS varbinary(MAX)) AS [Level] ,
c.[LevelID] + '>' + CAST (h2.AgentID AS varchar(max)) [LevelID],
CAST (H2.IntroducerID AS varchar(max)) [IntroducerID]
FROM
TblHierarchy H2
INNER JOIN
CTE c ON h2.RootID = c.AgentID
)
SELECT *
FROM CTE
CROSS APPLY
(SELECT
SUBSTRING(LevelID, 1, CHARINDEX('>', LevelID + '>') - 1) ) c(RootLevelID)
ORDER BY
[Level] DESC
OPTION (MAXRECURSION 0)
I do not fully understand your needs (especially what you are trying to achieve with all this casting...), but check this out:
EDIT: After some thinking I hope I got it
I removed my previous suggestion, where I had to change your input data. The following uses your input data unchanged and links via AgentID and RootID.
CREATE TABLE [dbo].[TblHierarchy](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[AgentID] [bigint] NULL,
[AgentName] [varchar](50) NULL,
[RootID] [bigint] NULL,
[IntroducerID] [bigint] NULL,
[Description] [varchar](50) NULL,
[HierarchyTree] [hierarchyid] NULL
) ON [PRIMARY];
INSERT [dbo].[TblHierarchy] ( [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES
( 1, N'Toh', 0, NULL, N'', NULL)
,( 2, N'Man', 1, 0, N'Child of Toh', NULL)
,( 3, N'Rul', 1, 0, N'Child of Toh', NULL)
,( 4, N'Rafiq', 2, 2, N'Child of Man', NULL)
,( 5, N'Paan', 2, 2, N'Child of Man', NULL)
SELECT * FROM dbo.TblHierarchy;
WITH recCTE AS
(
SELECT h.ID
,h.AgentID
,h.AgentName
,h.RootID
,h.IntroducerID
,h.[Description]
,CAST(h.[Description] AS VARCHAR(MAX)) AS HierDescr
FROM dbo.TblHierarchy AS h WHERE h.IntroducerID IS NULL
UNION ALL
SELECT h.ID
,h.AgentID
,h.AgentName
,h.RootID
,h.IntroducerID
,h.[Description]
,r.HierDescr + '/' + h.[Description]
FROM recCTE AS r
INNER JOIN dbo.TblHierarchy AS h ON h.RootID=r.AgentID
)
SELECT * FROM recCTE
GO
DROP TABLE [dbo].[TblHierarchy];

how to get table from first table when data is not there in second table

i have requirement where i need to show data of both tables when both the ID's are same.when id is present in first table and not there in second table i need to show data from first table
CREATE TABLE [dbo].[TEST](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Test_History](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Test_History] Script Date: 06/19/2015 19:01:49 ******/
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'A', CAST(0x0000A4BC01347E88 AS DateTime))
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'I', CAST(0x0000A4BC0134A390 AS DateTime))
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (2, N'Rohan', N'A', CAST(0x0000A4BC01391FCC AS DateTime))
/****** Object: Table [dbo].[TEST] Script Date: 06/19/2015 19:01:49 ******/
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (2, N'Rohan', N'I', CAST(0x0000A4BC0138D584 AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'A', CAST(0x0000A4BC013072DC AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (3, N'Raj', N'A', CAST(0x0000A4BC0138DED7 AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (4, N'Krishna', N'A', CAST(0x0000A4BC0138EE31 AS DateTime))
so far i have tried my query to achieve the result
select T.ID,COALESCE(T.ID,TT.ID),T.Name,COALESCE(T.Name,TT.Name),T.status,COALESCE(T.status,TT.status)
from Test T LEFT JOIN (Select TOP 1 ID,MIN(Name)name,Status from Test_History
GROUP BY ID,status
)TT
ON T.ID = TT.ID
where T.ID = 3
Id = 1 and 2 present show i will get data from both tables
Id = 3 and 4 not present in the table
so using coalesce i will get the data
from first table and show in 2nd table column also
but is there any other way like both tables are same structure
i'm thinking of
Declare #tablename varchar(10)
IF EXISTS (SELECT 1 from TESt where id = #id)
IF COunt there in both tables
SET #tablename = Test
ELSE
SET #tablename = Test_history
select * from #tablename where id = #ID
can i get any solution like this
You can use EXCEPT.
Here is an example:
SELECT a,b
FROM (
VALUES (1, 2), (3, 4), (5, 6), (7, 8), (9, 10)
) AS MyTable(a, b)
EXCEPT
SELECT a,b
FROM (
VALUES (1, 2), (7, 8), (9, 10)
) AS MyTable(a, b);
This will return all rows of the upper statement, which are not in the second statement.
First: Thanks for the excellent setup for the data related to the question!
If your real question was if table variables can be used as described in your question, the answer is no; or more accurately that its not worth it.
Not recommended:
declare #TableName TABLE (
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL)
IF EXISTS (SELECT 1 from TESt where id = #id)
INSERT INTO #TableName SELECT * FROM dbo.TEST WHERE ID = #ID
ELSE INSERT INTO #TableName SELECT * FROM dbo.[Test_History] WHERE ID = #ID
select * from #tablename where id = #ID
Here's the solution I prefer:
DECLARE #ID INT = 3;
SELECT * FROM [dbo].[TEST] ss WHERE ss.id = #id
UNION ALL SELECT * FROM [dbo].[Test_History] th WHERE th.id = #id
and not exists ( SELECT * FROM [dbo].[TEST] ss WHERE ss.id = #id);
UNION ALL performs surprisingly well - don't forget the ALL keyword, and I am assuming that ID is a PK or AK.
If I'm understanding correctly and you want to display all records that match between the two tables and only records from first table when the id does not exist in the second in the same result set, then all you need is a simple left join:
SELECT *
FROM dbo.test t
LEFT OUTER JOIN Test_History th
ON t.id = th.id
WHERE t.id = #id