I have written the below query to list all the rows in table [HRSurvey]
which empid is only present in empsurveyselection. Both table have empid columns.
But i am not able to get the proper results because there
might be multiple empid for same surveyid in empsurveyselection table.
But this query works fine when there is only one empid for each surveyid in empsurveyselection table.
Could you please rewrite the query to list the all the rows in the table HRSurvey where the empid are there in empsurveyselection ?
SELECT hrs.*
FROM [HRSurvey] hrs
Left Join [HRSurveyEmployee] hse
ON hse.EmpID = hrs.EmpID
LEFT Join Surveys s
ON s.surveyid = hse.surveyid
WHERE hrs.empid IN (
SELECT empid FROM [HRSurveyEmployee] where surveyid = s.surveyid
) and sempid
in ( select DISTINCT empid FROM empsurveyselection WHERE deptid=9 and surveyid = s.surveyid)
You can write as:
SELECT hrs.col1, -- Worst Practice to use * in production code to pull data
hrs.col12 -- Use explicit column names instead
FROM [HRSurvey] hrs
INNER JOIN [HRSurveyEmployee] hse ON hse.EmpID = hrs.EmpID
INNER JOIN [Surveys] s ON s.surveyid = hse.surveyid
INNER JOIN [empsurveyselection]ess ON ess.deptid=9
AND ess.surveyid = s.surveyid AND hrs.sempid = ess.empid
Please try with the below query....
select a.*
from HRSurvey a
where empid exists (select 1
from empsurveyselection b
where a.Empid = b.Empid)
Thanks for the help! Actually issue was not with the query. Issue was with the data and i fixed it.
Related
I am trying to make a sql query, that gets me the registration_timestamp of the newest comment.
By supplying a category id.
I have three tables. ( seen below with the fields that should be needed)
Ctm_Comments{
Id,
Page_ID,
Registration_Timestamp
}
Ctm_Forum_Categories{
Id
}
Ctm_Forum_Posts{
Id,
FK_Category_ID
}
I have tried the following, and it returns zero results.
var query = from p in Ctm_Forum_Posts
join c in Ctm_Forum_Categories on p.FK_Categori_ID equals c.Id
join ctm in Ctm_Comments on p.Id equals ctm.Page_ID
where c.Id == 1
select ctm.Reqistration_timestamp;
SQL Queries like these are not my strong suit, so i hope someone here can help out.
Ended up with this, based on the response from accepted answer.
var query = (from comments in Ctm_Comments
join posts in Ctm_Forum_Posts on comments.Page_ID equals posts.Id
join category in Ctm_Forum_Categories on posts.FK_Categori_ID equals category.Id
where category.Id == 1
orderby comments.Reqistration_timestamp descending
select comments.Reqistration_timestamp).FirstOrDefault();
SQL (MS SQL) Query needed is
SELECT TOP 1 [Registration_Timestamp]
FROM [dbo].[Ctm_Comments] AS C
INNER JOIN [dbo].[Ctm_Forum_Posts] AS P ON C.Page_ID = P.Id
INNER JOIN [dbo].[Ctm_Forum_Categories] AS CAT ON CAT.Id = P.Category_ID
WHERE CAT.Id = 1
ORDER BY C.Registration_Timestamp DESC
and this is if we accept that PageID (of Comments Table) is the Post Id. Otherwise, you are missing the PostId Column in the table of Comments which should be the join point
Run the Script below in SQL Server Studio for verification
CREATE TABLE [dbo].[Ctm_Comments] ( [Id] [int] NULL,[Page_ID] [int] NULL,[Registration_Timestamp] [datetime] NULL) ON [PRIMARY]
CREATE TABLE [dbo].[Ctm_Forum_Categories] ( [Id] [int] NULL) ON [PRIMARY]
CREATE TABLE [dbo].[Ctm_Forum_Posts] ( [Id] [int] NULL,[Category_ID] [int] NULL) ON [PRIMARY]
INSERT INTO [dbo].[Ctm_Comments] VALUES (1, 1, '2020-10-23 13:12:55')
INSERT INTO [dbo].[Ctm_Comments] VALUES (2, 1, '2020-10-26 12:12:55')
INSERT INTO [dbo].[Ctm_Comments] VALUES (3, 1, '2020-10-26 12:25:55')
INSERT INTO [dbo].[Ctm_Comments] VALUES (4, 1, '2020-10-26 13:12:55')
INSERT INTO [dbo].[Ctm_Forum_Categories] VALUES (1)
INSERT INTO [dbo].[Ctm_Forum_Posts] VALUES (1, 1)
SELECT TOP 1 [Registration_Timestamp]
FROM [dbo].[Ctm_Comments] AS C
INNER JOIN [dbo].[Ctm_Forum_Posts] AS P ON C.Page_ID = P.Id
INNER JOIN [dbo].[Ctm_Forum_Categories] AS CAT ON CAT.Id = P.Category_ID
WHERE CAT.Id = 1
ORDER BY C.Registration_Timestamp DESC
DROP TABLE [dbo].[Ctm_Comments]
DROP TABLE [dbo].[Ctm_Forum_Categories]
DROP TABLE [dbo].[Ctm_Forum_Posts]
the Result is 2020-10-26 13:12:55.000
When you fix the "my query returns 0 results" part, I'd suggest something like this:
var mostRecentCommentTimestamp = query.Max();
But as you've only selected timestamps, this can only tell you the max timestamp, nothing else about the comment
If you want the whole most recent comment swap the select for an order by descending on the timestamp and take the first*, or install morelinq and use their MaxBy
*Edit, like this:
var query = from p in Ctm_Forum_Posts
join c in Ctm_Forum_Categories on p.FK_Categori_ID equals c.Id
join ctm in Ctm_Comments on p.Id equals ctm.Page_ID
where c.Id == 1
orderby ctm.Reqistration_timestamp descending
select ctm;
var firstComment = query.First();
All this said, at the moment you say your query produces no results; you need to fix that (the joins are wrong, or there is no category 1, or the db is missing data) before you can get a max/orderby of anything
I'm trying to convert the following MySQL statement in to LINQ query format
SELECT * FROM table1 WHERE table1.id IN (SELECT c_id FROM table2 WHERE a_id IN (1, 49) GROUP BY c_id HAVING COUNT(*) = 2) ORDER BY name
Got as far as this, but I'm drawing a blank on how to handle the IN and 2nd SELECT statement
myItems = from c in table1
let id = c.id
where ????
orderby c.name
select c;
Would appreciate some guidance with this please
Try this:
var ids=new[]{1,49};
var innerquery=table2.Where(e=>ids.Contains(e.a_id))
.GroupBy(e=>e.c_id)
.Where(g=>g.Count()==2)
.Select(g=>g.Key);
var myItems = from c in table1
where innerquery.Contains(c.id)
orderby c.name
select c;
First define your inner query,after the group by you will get a collection of IGrouping<TKey, TElement>> that represent a collection of objects that have a common key, filter the groups choosing only those where count==2, and select the keys of those groups. The second part is really easy to understand. I split the process in two queries to do it more readable, but you can merge both query in one.
I have 7 tables and each table will contain an entry for a particular product.I want to check whether all 7 tables contains entry for a particular ID(eg: 4562). ie, data exists or not.I am using SQL server 2008.Please help me to write a query to check the status.
Try the following command (example for 3 tables T1,T2,T3). It returns 1 if ID = 4562 exists in ALL tables and 0 if at least one table miss this ID.
SELECT
CASE WHEN
(
EXISTS(SELECT ID FROM T1 WHERE ID=4562)
AND EXISTS(SELECT ID FROM T2 WHERE ID=4562)
AND EXISTS(SELECT ID FROM T3 WHERE ID=4562)
)
THEN 1
ELSE 0
END AS [ID_Exists_in_all_tables]
SQLFiddle demo
If you do a basic join rather than left join, the product will only appear if it's in all of the tables.
select * from tab1
join tab2 on tab2.id = tab1.id
join tab3 on tab3.id = tab1.id
join tab4 on tab4.id = tab1.id
join tab5 on tab5.id = tab1.id
Where tab1.id = 1234
etc etc
I have two tables Employee and Attendance, now i want date wise record both absent and present employee.
Like:--
Table1: Employee (EmpId,Name)
Table2: Attendance (Empid, CheckInOutDateTime, Status (like --I/O))
(Record will not available when Employee is Absent in Attendance Table but need record)
Now I want output:
**EmpID Name Date Status**
1 Emp1 06/11/2013 Persant
2 Emp2 06/11/2013 Absant
3 Emp3 06/11/2013 Persant
1 Emp1 06/12/2013 Persant
2 Emp2 06/12/2013 absant
3 Emp3 06/12/2013 absant
Try like this...
Select Empid,EmpName,Date1,(
cASE WHEN EXISTS(
SELECT EMPID FROM Atten AT WHERE T.EMPID=AT.EMPID AND T.date1=AT.Chechout
) then 'Present' Else 'Absent' End )as Status
FROM
(
Select Empid,EmpName,Cast(Chechout as DATE)AS DATE1 from Emp a,(Select Distinct Chechout from Atten) b
) T
in ms access-:
Select Empid,EmpName,Date1,(iif((SELECT Count(Empid)FROM Atten AT WHERE T.EMPID=AT.EMPID AND T.date1=DateVAlue(AT.Chechout))>0,'Absent','Present')) as Status
FROM(
Select Empid,EmpName,DateVAlue(Chechout) AS DATE1 from Emp a,(Select Distinct DateValue(Chechout) as Chechout from Atten) b
)T
SQL Fiddle Demo
The SQL feature you are looking for is called an outer join. You may also want to read up on the other SQL features.
If for whatever reason you cannot use an outer join, you can use a subselect and count the records in the attendance table because you are only interested in a boolean value, either there or not there for a given day (count > 0, employee was present, count = 0, employee was absent).
I could probably write a fancy query to get the results you want, but it would also require a 3rd table with every possible date.
I think it would be easier to have a scheduled task that added the absent records at the end of each day. Or you can make everyone absent ahead of time, then change the record to present as the employee shows up.
You can try this:
SELECT A.EmpId,A.Name,B.CheckInOutDateTime,status = CASE WHEN B.STATUS = 'IN' THEN 'PRESENT'
ELSE 'ABSENT' END from Table1 A join Table2 B ON A.Empid=B.empid
Here is the pseudo code:
for each date as varDate
query = "SELECT COUNT(*) AS cnt FROM Employee te LEFT JOIN Attendance ta ON te.Empid = ta.Empid WHERE ta.CheckInOutDateTime = " + varDate.ToString() + " GROUP BY te.Empid";
While displaying the result of above query, you can do this:
if Convert.ToInt32(dataRow("cnt")) > 0
status = "Present";
else
status = "Absent";
I have a problem that I know how to solve in SQL but not with Linq to Entities.
My data looks like this:
ID GROUP TIMESTAMP
-- ----- ---------
1 A 2011-06-20
2 A 2011-06-21
3 B 2011-06-21
4 B 2011-06-22
5 B 2011-06-23
6 C 2011-06-30
I want to retrieve all the Entity objects (not just the ID) such that I am only getting the most recent record from each group. (ie. the records with ids 2, 5, 6)
In SQL I would do something like this:
SELECT * FROM my_table a
WHERE a.timestamp =
(SELECT MAX(timestamp) FROM my_table b
WHERE a.group = b.group)
(For the sake of this question you can assume that timestamp is unique within each group).
I'd like to do this query against a WCF Data Service using Linq to Entities but I can't seem to have a nested query that references the outside query like this. Can anyone help?
Possibly not as clean and efficient as the hand written version but here's what I came up with
var q = from a in db.MyEntities
where a.Timestamp == (from b in db.MyEntities
where b.Group == a.Group
select b.Timestamp).Max()
select a;
which translates into this SQL
SELECT
[Project1].[Id] AS [Id],
[Project1].[Group] AS [Group],
[Project1].[Timestamp] AS [Timestamp]
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Group] AS [Group],
[Extent1].[Timestamp] AS [Timestamp],
[SSQTAB1].[A1] AS [C1]
FROM [MyEntities] AS [Extent1]
OUTER APPLY
(SELECT
MAX([Extent2].[Timestamp]) AS [A1]
FROM [MyEntities] AS [Extent2]
WHERE [Extent2].[Group] = [Extent1].[Group]) AS [SSQTAB1]
) AS [Project1]
WHERE [Project1].[Timestamp] = [Project1].[C1]
Hi try to use linqer that will convert your sql statements to linq query.
Linqer
Best Regards
This should work:
var query = db.my_table
.GroupBy(p=>p.group)
.Select(p=>p.OrderByDescending(q=>q.timestamp).First());
Here you go.A simple way to do.
var result = (from x in my_table
group x by x.Group into g
select new
{
g.Key,
timestamp = g.Max(x => x.TimeStamp),
g //This will return everything in g
});