SQL Server get parent list - sql-server

I have a table like this:
id name parent_id
1 ab1 3
2 ab2 5
3 ab3 2
4 ab4 null
5 ab5 null
6 ab6 null
I need to do a query with input id = 1 (for an example) and results will be like this:
id name parent_id
5 ab5 null
2 ab2 5
3 ab3 2
1 ab1 3
(List all parents at all level start at item id = 1)

Something like this perhaps?
WITH parents(id,name,parent,level)
AS
(
SELECT
ID,
NAME,
PARENT,
0 as level
FROM
TABLE
WHERE ID = 1
UNION ALL
SELECT
ID,
NAME,
PARENT,
Level + 1
FROM
TABLE
WHERE
id = (SELECT TOP 1 parent FROM parents order by level desc)
)
SELECT * FROM parents

Use WITH RECURSIVE. Documentation and adaptable example: Recursive Queries Using Common Table Expressions.

Related

T-SQL select rows where [col] = MIN([col])

I have a data set produced from a UNION query that aggregates data from 2 sources.
I want to select that data based on whether or not data was found in only of those sources,or both.
The data relevant parts of the set looks like this, there are a number of other columns:
row
preference
group
position
1
1
111
1
2
1
111
2
3
1
111
3
4
1
135
1
5
1
135
2
6
1
135
3
7
2
111
1
8
2
135
1
The [preference] column combined with the [group] column is what I'm trying to filter on, I want to return all the rows that have the same [preference] as the MIN([preference]) for each [group]
The desired output given the data above would be rows 1 -> 6
The [preference] column indicates the original source of the data in the UNION query so a legitimate data set could look like:
row
preference
group
position
1
1
111
1
2
1
111
2
3
1
111
3
4
2
111
1
5
2
135
1
In which case the desired output would be rows 1,2,3, & 5
What I can't work out is how to do (not real code):
SELECT * WHERE [preference] = MIN([preference]) PARTITION BY [group]
One way to do this is using RANK:
SELECT row
, preference
, [group]
, position
FROM (
SELECT row
, preference
, [group]
, position
, RANK() OVER (PARTITION BY [group] ORDER BY preference) AS seq
FROM t) t2
WHERE seq = 1
Demo here
Should by doable via simple inner join:
SELECT t1.*
FROM t AS t1
INNER JOIN (SELECT [group], MIN(preference) AS preference
FROM t
GROUP BY [group]
) t2 ON t1.[group] = t2.[group]
AND t1.preference = t2.preference

Finding an Hierarchy of row in SQL Server

I am unable to find the logic for below question in SQL Server.
I have a table like below.
id ParentID
---------------
1 NULL
2 NULL
3 1
4 2
5 3
6 5
I need a query which will return hierarchy of a row, like this:
Hierarchy id ParentID
----------------------------
1 1 NULL
1 2 NULL
2 3 1
2 4 2
3 5 3
4 6 5
I will explain the hierarchy:
For any row if ParentId is null then Hierarchy will be 1
Any row if ParentId is not null and ParentId's ParentId is null then 2
Any row if ParentId is not null, ParentId's ParentId is not null and next ParentId's ParentId is null then 3
And it goes on
How can write the query for this logic.
You can achieve this with a recursive query:
(in the below example your initial table data is stored in #a):
;With DATA AS (
SELECT 1 as hierarchy
,Id
,parentid
from #a
where parentid is null
UNION ALL
SELECT Data.Hierarchy + 1
,a.id
,a.parentid
FROM #a a
INNER JOIN DATA
ON Data.id = a.parentid
)
SELECT *
FROM DATA
ORDER BY hierarchy, Id

Using Recursive CTE with GroupBy

I am new to the recursive CTE concept and a problem at hand, I got a tiny feeling that the problem can be solved by using recursive CTE. Let me know what you guys think.
Two tables:
Table one is a self referencing Location table with ID, ParentID, Level and Description.
Table two is an asset table which records individual assets and has a foreign key to Location table ID field.
Table1:
ID Description ParentID Level
1 Site1 NULL 1
2 Site2 NULL 1
3 Building1 1 2
4 Building2 1 2
5 Floor1 3 3
6 Floor2 3 3
7 Floor3 4 3
8 Place1 5 4
9 Place2 7 4
Table2:
ID Description Quantity LocationID
1 Desk 3 8
2 Lamp 1 8
3 PC 10 9
I would like to create a stored procedure with a input parameter of #Level and returns all the Location records at that level and the number of assets within the location (including sub levels).
For example, if #Level = 3, the stored procedure should return:
ID Description AssetCount
5 Floor1 4
6 Floor2 0
7 Floor3 10
If #Level = 2, the stored procedure should return:
ID Description AssetCount
3 Building1 4
4 Building2 10
If the problem is not clear, please let me know.
Well, nothing special here, just a recursive CTE joined with the other table, and the results are what you expected:
declare #level int = 3
;with CTE as (
select id as origid, id, Description, parentid
from table1 where level = #level
union all
select CTE.origid, t1.id, CTE.Description, t1.parentid
from CTE join table1 t1 on
CTE.id = t1.parentid
)
select origid, CTE.description, isnull(sum(t2.Quantity),0) as Quantity
from CTE left outer join table2 t2 on CTE.id = t2.locationid
group by origid, CTE.description
SQL Fiddle

SQL Stored Procedures : Count, Join and group by but it is shown 'NULL'

I got stuck something about stored procedures I write a stored that i need to shot three columns of products count like this
SELECT
Count([TPDTN].[ProductName]) as 'Product Count',
[TPDTN].[CategoryID]
FROM
[TPDTN]
LEFT JOIN
[TPDCN] ON [TPDTN].[CategoryID] = [TPDCN].[libDocumentID]
GROUP BY
[TPDTN].[CategoryID], [TPDCN].[libDocumentID]
It shows results like this:
Product Count CategoryID
---------------------------
2 1
9 2
2 3
2 4
1 5
But I don't know how make it show
Product Count CategoryID libDocumentID
-----------------------------------------------
2 1 123456789
9 2 123456789
2 3 123456789
2 4 123456789
1 5 123456789
Producer ID (LibdocumentID) is from other table but when I SELECT [TPDCN].[libDocumentID] the value is NULL
Product Count CategoryID libDocumentID
------------------------------------------------
2 1 NULL
9 2 NULL
2 3 NULL
2 4 NULL
1 5 NULL
How can I solve it? Thank you
Just add it to the select, and if you don't need the NULL you need an INNER JOIN:
SELECT Count([TPDTN].[ProductName]) as 'Product Count',[TPDTN].[CategoryID], [TPDCN].[libDocumentID]
FROM [TPDTN]
inner join [TPDCN]
ON [TPDTN].[CategoryID] = [TPDCN].[libDocumentID]
GROUP BY [TPDTN].[CategoryID],[TPDCN].[libDocumentID]

SQL Server: Select Parent-Child

I have SQL Server 2008 with a table called ProductCategories designed like this:
Id | Name | ParentId
71 PCs NULL
32 MACs NULL
3 Keyboard 1
9 Mouse 1
5 Screen 1
11 Keyboard 2
7 Mouse 2
8 Screen 2
I would like to select from this table, and get a result set like this:
Id | Name | ParentId
71 PCs NULL
3 Keyboard 1
9 Mouse 1
5 Screen 1
32 MACs NULL
11 Keyboard 2
7 Mouse 2
8 Screen 2
I tried this, but that obviously gives me the ones with no ParentId first:
WITH Hierarchy
AS
(
SELECT
T1.Id, T1.ParentId
FROM
ProductCategories T1
WHERE
T1.parentid IS NULL OR
T1.parentid IN (SELECT id from ProductCategories WHERE parentid IS NULL)
UNION ALL
SELECT
T1.Id, T1.ParentId
FROM
ProductCategories T1
INNER JOIN
Hierarchy TH ON TH.Id = T1.ParentId
)
select *
from Hierarchy
order by parentid
Please help me, if you can :)
--
The guy who doesn't know SQL
try this:
Select Id, Name, ParentId
From ProductCategories
Order By Coalesce(ParentId, Id),
Coalesce(ParentId, 0), Name
Three Order By clauses,
Coalesce(ParentId, Id): This one groups the records by the parent, for both the parent itself and all the children of that parent
Coalesce(ParentId, 0) This groups within each set so that the one record with a null parent (the parent) sorts to the top within the group
Name, This sorts the children within the group by name
Try this
SELECT id, name, parentId
FROM categories
ORDER BY ISNULL(parentId,id), id
Btw, shouldn't first two indexes in your table be 1 and 2, not 71 and 32 ?

Resources