Subquery getting the parent addedby field - c#

Im trying to create a field called Owner in my table where You select the AddedBy field where parentID is equal to the PostID so far it only prints out the first field and the second is always null. Im doing a subquery on a query. Im trying to get the parent AddedBy field
SELECT Level, Sequence, PostID, AddedBy, Title, ParentID, Path_String,
CASE WHEN ParentID IS NULL THEN
AddedBy
ELSE
(SELECT AddedBy FROM cte o WHERE o.PostID = ParentID)
END AS Owner
FROM cte order by Sequence
Im trying to get a count of all posts that related to the PostID joinded by ParentID in a join but im getting an error so when i do a group by of all the Fields i still get the error:- error is below
SELECT s.Level, s.Sequence, s.PostID, s.AddedBy,
s.Title, s.ParentID, s.Path_String,
Owner = COALESCE(o.AddedBy, s.AddedBy), COUNT(r.ParentID)
FROM cte AS s
LEFT OUTER JOIN cte AS o
ON s.ParentID = o.PostID
RIGHT join cte AS r
on s.PostID = r.ParentID
ORDER BY s.Sequence;
i get the following error:
Msg 8120, Level 16, State 1, Procedure sproc_GetPostsByThread, Line 34
Column 'cte.Level' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
PostID, ParentID, AddedBy, Title, Path_String:- PostID is IdentityColumn Path_String is in this format 1/, 1/1/, 1/1/2 and ParentID is an integer
Level Sequence PostID AddedBy Title ParentID Path_String Owner Count
1 00000003 3 kirkdm test NULL 3/ kirkdm 1
2 0000000300000005 5 MikeDM re: test 3 3/5/ kirkdm 2
3 000000030000000500000008 8 Joelene re: test 5 3/5/8/ MikeDM 2
3 000000030000000500000009 9 kirkdm re: test 5 3/5/9/ MikeDM 1
4 00000003000000050000000900000010 10 Crushanin re: test 9 3/5/9/10/ kirkdm 1
Should be this
Level Sequence PostID AddedBy Title ParentID Path_String Owner Count column here
1 00000003 3 kirkdm test NULL 3/ kirkdm
2 0000000300000005 5 MikeDM re: test 3 3/5/ kirkdm
3 000000030000000500000008 8 Joelene re: test 5 3/5/8/ MikeDM
4 00000003000000050000000800000014 14 Christian re: test 8 3/5/8/14/ Joelene
4 00000003000000050000000800000015 15 Zeke re: test 8 3/5/8/15/ Joelene
3 000000030000000500000009 9 kirkdm re: test 5 3/5/9/ MikeDM
4 00000003000000050000000900000010 10 Crushanin re: test 9 3/5/9/10/ kirkdm
5 0000000300000005000000090000001000000011 11 Tim re: test 10 3/5/9/10/11/ Crushanin

SELECT s.Level, s.Sequence, s.PostID, s.AddedBy,
s.Title, s.ParentID, s.Path_String,
Owner = COALESCE(o.AddedBy, s.AddedBy)
FROM cte AS s
LEFT OUTER JOIN cte AS o
ON s.ParentID = o.PostID
ORDER BY s.Sequence;

Related

Get employees from a manager which is from another period

We have a employee table like
Employee ID
Name
EmployeeManager table like
employeeid
employeeManagerid
intyear
intperiod
So every manager is an employee, employeemanagerid is the forigen key from employee table and it is an employeeid from the employee table
An employee can have multiple managers in a year that is the reason for
intYear and intPeriod, intPeriod is the month so it will have value from 1-12
What i am trying to achieve is if a manager is selected in one period(months) and no manager is assigned for next three periods(months) then the same manager
will be assigned to that guy,
to give an example
employee table
----------------------------------------------------------------
employeeid name
1 a
2 b
3 c
4 d
5 e
-------------------------------------------------------------------
EmployeeManager table
----------------------------------------------------------------------
employeeid employeemanagerid intyear intperiod
-----------------------------------------------------------------------
1 5 2017 3
1 4 2017 4
2 4 2017 6
3 4 2017 6
------------------------------------------------------------------------
My query
select e.name,e.employeeid
from employee e
left join employeemanager em
on e.employeeid = em.employeeid
where
em.employeemanagerid = #managerid
and em.intyear = #intyear
and em.intperiod <= #intperiod
the values supplied as a parameter are
#managerid = 4
#intyear = 6
#intperiod = 2017
What i want as expected result is
------------------------------------------------------
name employeeid
a 1
b 2
c 3
------------------------------
Employee b,c is straight match but a has the manger set in period 4 which
is still continueing till period 6
what i should change in the query to get this result
the parameter values are sent from c#.
The problem is you are filtering out all records that are not for a specific manager, but you still expect those records to affect the results. You are also not doing anything to stop duplicates, if you had an employee go from manager 4 to 5 to 4 it would show twice. You need to get a query first that figures out who the correct manager is for each row for the period wanted, then do your main query from that first query. One way to do this is:
--This gets all manager records for the period (or before), with a rowno added
--sorted so that the most recent manager is always number 1
With emData as
(
Select employeeid, employeeManagerid, intyear, intperiod
, ROW_NUMBER() OVER(Partition by employeeid ORDER BY intyear DESC, intperiod DESC) as RowNo
from employeemanager
where intyear <= #intyear
and intperiod <=#intperiod
)
--This is your original query, changed to use the above as the source
select e.name,e.employeeid
from employee e inner join
emData em on e.employeeid = em.employeeid
where
em.employeemanagerid = #managerid
and em.RowNo = 1 --THIS MAKES SURE YOU ARE ONLY LOOKING AT THE MOST RECENT MANAGER

SQL hiearchy select query between two tables

I have 2 tables (People, Department).
Department table look like this:
ID (int)
Name (varchar)
ParentID (int)
People table like this:
Id (int)
FirstName (varchar)
SureName (varchar)
DepartmentId (int)
Manager (Bool)
Asistant (Bool)
I need to create query, which select all direct subordinates of concrete person which is manager of concrete depertment. And one query which select all not only direct subordinates of manager.
Each department have one manager and one asistant. The peoples with manager == false are direct subordinates, and peoples in child depertment are subordinates of parent depratment .
I have no idea how to crete this queries in SQL / LINQ.
I will be grateful for any help!
Example:
DEPARTMENT
Id Name Parent
0 Department1 null
1 Department2 0
2 Department3 1
Example:
People
ID Name Department DepartmentId Manager Asistant
1 Martin Joshua 0 1 0
2 Ondra Joshua2 0 0 0
3 Petr Joshua3 0 0 0
4 Todd Joshua3 1 1 0
5 Alex Joshua3 1 0 0
6 Iva Joshua3 1 0 0
7 Otto Joshua3 2 1 0
8 Todd Joshua3 2 0 0
I need for exmple select all (not only direct) subordinates of manager in deparment with id 0, result wil look like:
2 Ondra Joshua2 0 0 0
3 Petr Joshua3 0 0 0
4 Todd Joshua3 1 1 0
5 Alex Joshua3 1 0 0
6 Iva Joshua3 1 0 0
7 Otto Joshua3 2 1 0
8 Todd Joshua3 2 0 0
I´m not sure direct subordinates SQL query:
SELECT * FROM dbo.PeopleView WHERE DepartmentId = 162 AND Manager = 0; -- all direct s (162)
SOLUTION:
;WITH CTE AS
(
SELECT 1 as EMPLEVEL, H1.Id, H1.ParentId, H1.Name FROM DepartmentView H1 WHERE Id = 6
UNION ALL
SELECT EMPLEVEL + 1, H2.Id, H2.ParentId, H2.Name FROM DepartmentView H2
INNER JOIN CTE ON H2.ParentId = CTE.Id
)
SELECT DISTINCT P.Id, P.LastName,P.FirstName,P.DepartmentId,P.Manager,P.Assistant FROM CTE as T JOIN PeopleView as P on T.Id = P.DepartmentId;
In adition to your first query, and like a comment from #Andrew says, a recursive query can help with this:
;WITH CTE
AS
(
SELECT ID,FirstName,SureName,DepartmentID,Manager,Assistant, 0 AS EMPLEVEL FROM PEOPLE A WHERE DepartmentId = 1 AND Manager = 0
UNION ALL
SELECT B.ID,B.FirstName,B.SureName,B.DepartmentID,B.Manager,B.Assistant,EMPLEVEL +1 FROM PEOPLE B
INNER JOIN DEPARTMENT D
ON B.DepartmentID = D.ID
INNER JOIN CTE
ON D.ParentID = CTE.DepartmentID
)
SELECT DISTINCT * FROM CTE
And for convert to LINQ, you can read this post :P:
Common Table Expression (CTE) in linq-to-sql?
Hope this help, best regards.

Problems in Right join in SQl

I have the following table structure also i have mention my expected output
please help me with query as i dont know much about sql query
Table Structure
Table 1 : Emp Details
FName Id
Pratik 1
Praveen 3
Nilesh 2
Table 1 : JoinigDocument
id DocumentName
1 Leaving
2 Exp letter
3 birth cert
Table 2 : EmployeeJoiningDocument
EmpId JoiningDocumentId
1 1
1 2
3 1
3 2
3 3
2 1
2 3
Expected Output :
FName Id JoiningDocumentId DocumentName
Pratik 1 1 Leaving
Pratik 1 2 Exp letter
Pratik 1 null birth cert
Praveen 3 1 Leaving
Praveen 3 2 Exp letter
Praveen 3 3 birth cert
Nilesh 2 1 Leaving
Nilesh 2 null Exp letter
Nilesh 2 3 birth cert
You can write a query as:
select
A.FName,
A.Id,
B.JoiningDocumentId,
c.DocumentName
from #JoinigDocument C
cross join #EmployeeDetail A
Left join #EmployeeJoiningDocument B on B.EmployeeId = A.id and
B.JoiningDocumentId = C.id
order by A.Id
First cross join JoinigDocument and EmployeeDetail table so that you get all possible combinations of Employee and Documents irrespective of the fact that employee has that Joining Document or not. Then you need to do a left join to retain all these matches and find data corresponding to valid entries in EmployeeJoiningDocument.
Demo

SQL query to get matching records from Table1 and Table2 with a custom column showing 1/0 if data is present

I have several table related to multilingual Photo Galley like
AlbumCategories
AlbumName
Photos
PhotoDetails
Sample Table Structure of two table. I actually want a result set that will show me list of all records from Photos Table for particular AlbumID along with a custom column that will show TRUE or FALSE based on if particular PhotoID is present in the PhotoDetails Table
Table: Photos
PhotoID PhotoFile AlbumID
1 Photo1.jpg 7
2 Photo2.jpg 7
3 Photo3.jpg 5
4 Photo4.jpg 5
5 Photo5.jpg 7
6 Photo6.jpg 7
Table: PhotoDetails
PDID PhotoID PDTitle AlbumID LanguageID
11 1 Photo 1 7 1
22 2 Photo 2 7 1
33 3 Photo 3 5 1
44 4 Photo 4 5 1
DESIRED OUT PUT
PhotoID PDTitle AlbumID DetailPresent
1 Photo1 7 TRUE
2 Photo2 7 TRUE
5 Photo5 7 FALSE
6 Photo6 7 FALSE
I tried something several JOIN based queries but could not get the desired result
SELECT pd.PhotoTitle, p.PhotoTN,p.PhotoCreatedOn, pd.AlbumID, ISNULL(p.PhotoID,NULL) AS Missing FROM AlbumPhotos p
JOIN AlbumPhotoDetails pd
ON p.PhotoID = pd.PhotoID WHERE pd.AlbumID = 16
This query gives me the same result
SELECT pd.PhotoTitle, p.PhotoTN,p.PhotoCreatedOn, pd.AlbumID, ISNULL(p.PhotoID,NULL) AS Missing FROM AlbumPhotos p
JOIN AlbumPhotoDetails pd
ON p.PhotoID = pd.PhotoID WHERE pd.AlbumID = 16
OR p.PhotoID IN (SELECT PhotoID FROM AlbumPhotoDetails WHERE LanguageID = 1 AND AlbumID = 16)
Above query get me the result of matching based on PhotoID. I am lost how i can actually achieve the desired result as shown in the above sample 'DESIRED OUT PUT`
Use a left outer join.
The table examples that you have shown doesn't make any sense, as there is no field to connect them, and the PDTitle values that you want in the result doesn't exist in the example data.
Assuming that there is a PhotoId field in the PhotoDetails table (like in the AlbumPhotoDetails table that you use in the query that you show), and that the PhotoDetails table contains the titles that you want in the result, you can do like this:
select
p.PhotoId, d.PDTitle, p.AlbumId,
case when d.PhotoId is null then 'FALSE' else 'TRUE' end
from Photos p
left join PhotoDetails d on d.PhotoId = p.PhotoId
where p.AlbumId = 7
Note that the title will be null where there are no corresponding record in the PhotoDetails table.

How to do recursive query using a temporary table in Mysql

OrganisationID OrganisationName parentID
1 Org1 Null
2 Org2 1
3 Org3 1
4 Org4 2
5 Org5 2
6 Org5 4
Table Name is tbl_Organisation
I am having a table similar to this. All I am trying is to retreive the Sub Organisation and display it. Suppose the Org ID passed is 3, then the Org3 doesnt have any child so it displays only Org3. Suppose if OrgID =2 then the Org2 has a child Org4 and Org4 has a child Org5. So for OrgID=2 I have to display Org2, Org4 and Or5. SO how can I do that. I have tried few things but it didn't work as I intended.
SELECT distinct b.OrganisationID,b.OrganisationName
FROM tbl_organisation as a LEFT OUTER JOIN tbl_organisation as b
on a.OrganisationID=b.ParentID where a.OrganisationID=b.parentID
Tell me where I am wrong
I am using this in asp.net website, I am using c# and mysql
This is related to Hierarchail Query:
SELECT (LPAD(' ', level * 3, ' ')||OrganisationID) as Org_id,
OrganisationName,
parentID,
LEVEL
FROM tbl_Organisation
START WITH OrganisationID = ---
Comment: Pass the Organisation ID here
CONNECT BY PRIOR OrganisationID = parentID
If you pass 1 as the OrganizationID then the Output will be
Org_id OrganisationName parentID LEVEL
1 Org1 1
2 Org2 1 2
4 Org4 2 3
6 Org6 4 4
5 Org4 2 3
3 Org2 1 2

Categories

Resources