Re-writting the query without "Connect By " - sql

I am rewriting the query to replace to remove CONNECT BY:
SELECT *
FROM ADM_TRT AT
INNER JOIN UTILISATEUR U
ON U.UTI_ID = AT.UTI_ID
INNER JOIN
(
SELECT CM.MAI_ID
FROM CON_MAI CM
CONNECT BY CM.MAI_PER_RES = PRIOR CM.MAI_ID
START WITH CM.MAI_ID IN (
SELECT MAJ_ID
FROM DROIT_LOGIN
WHERE LOG_ID = 21543
)
) CON_MAI_FILTERED_ON_LOGIN
ON AT.TRT_MAI_ID = CON_MAI_FILTERED_ON_LOGIN.MAI_ID;
For CONNECT BY Part , I wrote this
WITH tree (MAI_ID,MAI_PER_RES, level1) AS (
SELECT MAI_PER_RES, MAI_ID, 1 as level1 FROM CON_MAI
UNION ALL
SELECT child.MAI_ID, child.MAI_PER_RES, parent.level1 + 1
FROM CON_MAI child --Line 20
JOIN tree parent
on parent.MAI_PER_RES = child.MAI_ID
)
SELECT MAI_ID FROM tree
But I am stuck to integrate this in subquery in the CONNECT BY sub-query. Can someone please help to integrate this?

It looks like you have the recursion reversed in the recursive sub-query and can use:
WITH tree (MAI_ID) AS (
SELECT MAI_ID
FROM CON_MAI
WHERE MAI_ID IN ( SELECT MAJ_ID
FROM DROIT_LOGIN
WHERE LOG_ID = 21543 )
UNION ALL
SELECT c.MAI_ID
FROM CON_MAI c
JOIN tree p
on c.MAI_PER_RES = p.MAI_ID
)
SELECT *
FROM ADM_TRT AT
INNER JOIN UTILISATEUR U
ON U.UTI_ID = AT.UTI_ID
INNER JOIN tree CON_MAI_FILTERED_ON_LOGIN
ON AT.TRT_MAI_ID = CON_MAI_FILTERED_ON_LOGIN.MAI_ID;
(untested as I do not have your tables or data)

Related

Can you help me to write recursive query for two tables?

I need to write recursive query for finding all child nodes in this tables.
For example i need find all child ExecutorTasks for ParentManagerTaskId = 6
ManagerTasks
{
Id,
ParentExecutorTaskId
}
ExecutorTasks
{
Id,
ParentManagerTaskId
}
;WITH query AS
(
SELECT et.Id,et.ParentManagerTaskId,mt.ParentExecutorTaskId
FROM [Planning.ExecutorTasks] et
left outer join [Planning.ManagerTasks] mt on et.ParentManagerTaskId=mt.Id
WHERE mt.Id = 6
UNION ALL
SELECT q.Id, q.ParentManagerTaskId,et.Id
FROM [Planning.ExecutorTasks] et
JOIN query q ON et.Id = q.Id
)
SELECT *
FROM query
Your model is a little misleading since you have 2 tables that are related against each other and you only want to display records from one. This means you have to do 2 joins on the recursive part to get the children of the related entity.
Try with the following:
;WITH Recursion AS
(
-- Anchor
SELECT
ExecutorTaskId = E.Id,
RecursionLevel = 0
FROM
[Planning.ExecutorTasks] AS E
WHERE
E.ParentManagerTaskId = 6
UNION ALL
-- Further childs
SELECT
ExecutorTaskId = E.Id,
RecursionLevel = R.RecursionLevel + 1
FROM
Recursion AS R
INNER JOIN [Planning.ManagerTasks] AS M ON R.ExecutorTaskId = M.ParentExecutorTaskId
INNER JOIN [Planning.ExecutorTasks] AS E ON M.Id = E.ParentManagerTaskId
)
SELECT
R.RecursionLevel,
R.ExecutorTaskId
FROM
Recursion AS R
ORDER BY
R.RecursionLevel,
R.ExecutorTaskId
I can't test if you don't supply example values, expected outcome and table's DDL.

Get all parents for a child in postgresql

I have been runed success On SQL Server. My System run on SQL Server and postgresql.
But when I change from SQL Server to postgresql it running fail.
My sql like this:
with name_tree as
(
SELECT DepartNo, ParentNo FROM Departments
WHERE DepartNo IN (
SELECT DepartNo FROM BelongToDepartment
WHERE UserNo = 1)
union all
select C.DepartNo, C.ParentNo
from Departments c
join name_tree p on C.DepartNo = P.ParentNo
AND C.DepartNo<>C.ParentNo
)
select * from name_tree
The error is:
name_tree doesn't exist
How can get all parents for a child in postgresql
More detail in MSQ Server here
Try:
with RECURSIVE name_tree as
(
SELECT DepartNo, ParentNo FROM Departments
WHERE DepartNo IN (
SELECT DepartNo FROM BelongToDepartment
WHERE UserNo = 1)
union all
select C.DepartNo, C.ParentNo
from Departments c
join name_tree p on C.DepartNo = P.ParentNo
AND C.DepartNo<>C.ParentNo
)
select * from name_tree

SQL hide rows specifically

This is my table structure and sample rows:
And I have a SQL query like this :
WITH Test(ObjId, ObjectIcerik, KeyMi) AS
(
SELECT
ObjId, ObjectIcerik, KeyMi
FROM
Tek
WHERE
ObjId = 8
UNION ALL
SELECT
T.ObjId, T.ObjectIcerik, T.KeyMi
FROM
Tek T
INNER JOIN
Test as TE ON T.ObjParent = TE.ObjId
)
SELECT *
FROM Test
This is the result :
But I also need to hide parent and child rows if parent's KeyMi column is '1'.
What do I need to change in the SQL query to do this?
You should be able to just add the condition to the recursive CTE:
WITH Test(ObjId, ObjectIcerik, KeyMi) AS (
SELECT ObjId, ObjectIcerik, KeyMi FROM Tek
WHERE ObjId = 8 AND (KeyMI <> 1 OR KeyMI IS NULL)
UNION ALL
SELECT T.ObjId, T.ObjectIcerik, T.KeyMi
FROM Tek T INNER JOIN
Test TE
ON T.ObjParent = TE.ObjId
WHERE (t.KeyMI <> 1 OR t.KeyMI IS NULL)
)
SELECT *
FROM Test ;

Existing query optimization

We have 5 tables and we are trying to create a view to get the results.
Below is the view which is working fine.
I need suggestions. Is it a good practice to write this query in this way or it can be optimized in a better way.
SELECT p.Pid, hc.hcid, hc.Accomodation, ghc.ghcid, ghc.ProductFeatures, wp.existing, wp.acute, mc.cardiaccover, mc.cardiaclimitationperiod
FROM TableA p
LEFT JOIN TableB hc
ON p.pid = hc.pid
LEFT JOIN TableC ghc
ON p.pid = ghc.pid
LEFT JOIN (SELECT *
FROM (SELECT hcid,
title,
wperiodvalue + '-' + CASE WHEN
wperiodvalue > 1 THEN
unit +
's' ELSE
unit END wperiod
FROM TableD) d
PIVOT ( Max(wperiod)
FOR title IN (acute,
existing
) ) piv1) wp
ON hc.hcid = wp.hcid
LEFT JOIN (SELECT *
FROM (SELECT hcid,
title + col new_col,
value
FROM TableE
CROSS apply ( VALUES (cover,
'Cover'),
(Cast(limitationperiod AS
VARCHAR
(10)),
'LimitationPeriod') ) x (value, col
)) d
PIVOT ( Max(value)
FOR new_col IN (cardiaccover,
cardiaclimitationperiod,
cataracteyelenscover,
cataracteyelenslimitationperiod
) ) piv2) mc
ON hc.hcid = mc.hcid
Any suggestions would be appreciated.
Thanks
My suggestion is to break down the query using temporary table, create stored procedure then dump data in the one new table and with the help of that table you can create view:
Store both PIVOT result in tow seperate temp tables as
SELECT * INTO #pvtInfo FROM ( --first PIVOT query
SELECT * INTO #pvtInfoTwo FROM ( --second PIVOT query
Then your final query will be as :
SELECT p.Pid,
hc.hcid,
hc.Accomodation,
ghc.ghcid,
ghc.ProductFeatures,
wp.existing,
wp.acute,
mc.cardiaccover,
mc.cardiaclimitationperiod
FROM TableA p
LEFT JOIN TableB hc ON p.pid = hc.pid
LEFT JOIN TableC ghc ON p.pid = ghc.pid
LEFT JOIN #pvtInfo wp ON hc.hcid = wp.hcid
LEFT JOIN #pvtInfoTwo mc ON hc.hcid = mc.hcid
First you can try then only go with SP and VIEW.
Hope, It will help.

Tree view using SQL Query

I have a regions table of which I want a tree view (table simple ordered as tree) is it possible using sql queries help is appreciated, I tried to do it using self joins but i did not get the desired result.
tree view is something like this
Indiv
Div1
Zon1
div2
zon2
div3
zon3
EDIT:
as per Charles Bretana suggetion I tried CTE in below query and it did not give me desired result.
WITH Emp_CTE (id, ParentID, name)
AS (
SELECT id, ParentID, name
FROM eQPortal_Region
WHERE ParentID=0
UNION ALL
SELECT e.id, e.ParentID, e.name
FROM eQPortal_Region e
INNER JOIN Emp_CTE ecte ON ecte.id = e.ParentID
)
SELECT *
FROM Emp_CTE
GO
This is the result .. what went wrong ?
InDiv1
Div1
Div2
Div3
Zon3
Zon2
zon1
This guy Maulik Dhorajia answers the question perfectly ...
http://maulikdhorajia.blogspot.com/2012/06/sql-server-using-ctecommon-table.html
Made a replica of the query ..
;WITH CTECompany
AS
(
SELECT
ID,
ParentID,
Name ,
0 AS HLevel,
CAST(RIGHT(REPLICATE('_',5) + CONVERT(VARCHAR(20),ID),20) AS VARCHAR(MAX)) AS OrderByField
FROM Region
WHERE ParentID = 0
UNION ALL
SELECT
C.ID,
C.ParentID,
C.Name ,
(CTE.HLevel + 1) AS HLevel,
CTE.OrderByField + CAST(RIGHT(REPLICATE('_',5) + CONVERT(VARCHAR(20),C.ID),20) AS VARCHAR(MAX)) AS OrderByField
FROM Region C
INNER JOIN CTECompany CTE ON CTE.ID = C.ParentID
WHERE C.ParentID IS NOT NULL
)
-- Working Example
SELECT
ID
, ParentID
, HLevel
, Name
, (REPLICATE( '----' , HLevel ) + Name) AS Hierachy
FROM CTECompany
ORDER BY OrderByField
See the following sample SQL script:
DECLARE #lV NCHAR(1)=NCHAR(9474),#lR NCHAR(1)=NCHAR(9500),#lU NCHAR(1)=NCHAR(9492),#spc NCHAR(1)=' ';
WITH data AS(SELECT * FROM(VALUES(1,'0','In Div1',1),(2,'1','Div1',1),(3,'2','zon1',1),(4,'1','Div2',2),(5,'1','Div3',3),(6,'4','Zon2',1),(7,'5','Zon3',1))t([ID],[ParentID],[Name],[SeqOrder])
),d_root AS(SELECT CAST('/'AS NVARCHAR(MAX))[n_path],* FROM data WHERE ParentID='0'
),d_cte AS(SELECT b.n_path+CAST(ROW_NUMBER()OVER(ORDER BY a.ID)AS NVARCHAR(MAX))+'/'[n_path],a.* FROM data a INNER JOIN d_root b ON a.ParentID=b.ID UNION ALL SELECT b.n_path+CAST(ROW_NUMBER()OVER(ORDER BY a.ID)AS NVARCHAR(MAX))+'/'[n_path],a.* FROM data A INNER JOIN d_cte b ON a.ParentID=b.ID
),Tree_BASE AS (SELECT CAST(n_path AS HIERARCHYID)[h_id],* FROM d_root UNION ALL SELECT CAST(n_path AS HIERARCHYID)[h_id],* FROM d_cte
),cte_o AS(SELECT a.h_id,CASE WHEN EXISTS(SELECT * FROM Tree_BASE WHERE h_id>b.h_id AND h_id.GetAncestor(1)=b.h_id.GetAncestor(1))THEN #lV ELSE #spc END[t_l] FROM Tree_BASE a INNER JOIN Tree_BASE b ON a.h_id.IsDescendantOf(b.h_id)=1 AND NOT b.h_id=HIERARCHYID::GetRoot()
),cte_m AS(SELECT x.*,(SELECT t_l+'' FROM cte_o WHERE h_id=x.h_id FOR XML PATH(''))[b_tree] FROM Tree_BASE x
),cte_h AS(SELECT ISNULL(LEFT(b_tree,LEN(b_tree)-1)+CASE WHEN EXISTS(SELECT * FROM Tree_BASE WHERE h_id>a.h_id AND h_id.GetAncestor(1)=a.h_id.GetAncestor(1))THEN #lR ELSE #lU END,'')+' '+RTRIM(Name) [TreeV],a.h_id FROM cte_m a
)SELECT b.TreeV,ROW_NUMBER()OVER(ORDER BY a.h_id ASC)[row_id]FROM Tree_BASE a INNER JOIN cte_h b ON a.h_id=b.h_id ORDER BY row_id