In my database i have column name department and employed(return type is bit - 0 or 1), i would like to count the number of employee employed in each department (there are 5 departments) for this year and rank the department who has the highest employee. I need help combining SQL query.
This is how i can calculate 0'1 and 1's SELECT COUNT(CASE Authorised WHEN 1 THEN 1 ELSE NULL END) FROM TableName;
and this is how i can select date for this year: `
SELECT distinct *
From TableName
WHERE Time BETWEEN CONVERT(Date,#Time) AND CONVERT(Date, #Time2)
How do i combine these query?
You need to use this query, the query returns all departments name and the total of employees in it.
SELECT
DEPARTMENTNAME, COUNT(*) AS TOTAL
FROM
TABLENAME
WHERE
TIME BETWEEN
CONVERT(Date,#Time)
AND
CONVERT(Date, #Time2)
GROUP BY DEPARTMENTNAME
ORDER BY COUNT(*) DESC
This is an example of how your sql should be.
declare #WhatEverYourTableNameIs Table
(
Department varchar(3),
employed bit,
employeddate date
)
Insert into #WhatEverYourTableNameIs
Values
('dem',1,'2014-1-1'),
('dem',1,'2014-2-1'),
('dem',0,'2014-2-1'),
('eem',1,'2013-2-1'),
('dem',1,'2013-2-1'),
('eem',1,'2014-2-1')
Select Department, Count(employed) AS Cnt
From #WhatEverYourTableNameIs
Where employeddate >'2013-12-31' and employed = 1
Group by Department
order by Cnt desc
Related
In short:
I have records that have CreationTime column in database. I want to select records from last 2 days PLUS one record that follows (sort by creation date desc) that can be any time old.
So from records (knowing that today date is 11th March) I want to select all records that are at max 2 days old + 1:
1. 2019-03-11
2. 2019-03-11
3. 2019-03-10
4. 2019-03-08
5. 2019-03-07
6. 2019-03-16
So result should contain records 1,2,3,4. (4. even though it is 3 days old, it is that "+1" record I need).
I'm using MSSQL and .NET 4.6.1 Entity Framework.
IMO cleaner way to achieve this is to write two queries: first to get data from last two days and second is to get the latest record older than 2 days.
To get records from last 2 days:
select * from MyTable where CreationTime between getdate() and getdate() - 2
To get additional record:
select top 1 * from MyTable where CreationTme < getdate() - 2 order by CreationTime desc
Using EF with LINQ methods (dc is database context):
To get records from last 2 days:
dc.Entitites.Where(e => e.CreationTime <= DateTime.Now && e.CreationTime >= DateTime.Now.AddDays(-2));
additional record:
dc.Entities.Where(e => e.CreationTime < DateTime.Now.AddDays(-2)).OrderByDescending(e => e.CreationTime).First();
Try the following Logic
DECLARE #T TABLE
(
SeqNo INT IDENTITY(1,1),
MyDate DATETIME
)
INSERT INTO #T
VALUES(GETDATE())
,(DATEADD(MINUTE,-23,GETDATE()))
,(DATEADD(MINUTE,-78,GETDATE()))
,(DATEADD(MINUTE,-5443,GETDATE()))
,(DATEADD(MINUTE,-34,GETDATE()))
,(DATEADD(MINUTE,-360,GETDATE()))
,(DATEADD(MINUTE,-900,GETDATE()))
,(DATEADD(MINUTE,-1240,GETDATE()))
,(DATEADD(MINUTE,-3600,GETDATE()))
;WITH CTE
AS
(
SELECT
RN = ROW_NUMBER() OVER(PARTITION BY CAST(MyDate AS DATE) ORDER BY MyDate DESC),
DateSeq = DATEDIFF(DAY,MyDate,GETDATE()),
*
FROM #T
)
SELECT
*
FROM CTE
WHERE
DateSeq <2
OR
(
DateSeq = 2
AND
RN = 1
)
You can try the following query.
DECLARE #table TABLE(StartDate DATETIME)
INSERT INTO #table
VALUES('2019-03-11'),('2019-03-11'),('2019-03-10'),
('2019-03-08'),('2019-03-07'),('2019-03-16')
SELECT * FROM #table WHERE StartDate BETWEEN GETDATE()-4 AND GETDATE()
For getting old 4th entry,
SELECT * FROM #table
ORDER BY (select null)
OFFSET (select Count(*) from #table where StartDate BETWEEN GETDATE()-2 AND
GETDATE()) ROWS
FETCH NEXT 1 ROWS ONLY
If I try to select 2 columns, i get an error message that says, Ambiguous column name 'signed_in'. Name of the tables are UserName and Meeting. Please help
select count(*)
FROM UserName, Meeting
where YEAR(signed_in ) = datepart(YEAR, getdate());
It means that the signed_in column is present in both UserName and Meeting tables. You need to prefix the column with a table name like this:
UserName.signed_in or Meeting.signed_in
Thank you all for your answers, I really appreciate.
I have sorted it out using the following code:
select
( select count() from UserName where YEAR(signed_in ) = datepart(YEAR, getdate()) )
+
( select count() from Meeting where YEAR(signed_in ) = datepart(YEAR, getdate()))
and the total count for the both tables display in one column, one row. totaling 7 which represents 5 from UserName table and 2 from Meeting table.
I have 2 tables in SQL Server, Table1 and Table2.
Table1 contains the information of family head with his age and Table2 contains the information of family members with their age.
I want to get total count of age. Means if the user enter less than 23 in front end so I will display to user total count of persons less than 23 age from two tables.
My approach is like this:
alter procedure example
(#age int, #result2 int output)
as
begin
declare #result int;
declare #result1 int;
set #result = (select count(age) from Table1 where age > #age)
set #result1 = (select count(age) from Table2 where age > #age)
set #result2 = #result + #result1;
end
hvcid is the primary key column in my Table1 and hvcid is a foreign key in my Table2.
My query shown above returns the result fine. Why not do using join or single query to combine two tables and get the total count of age from two tables?
I don't know how to write using single query? Can you solve my issue?
You can use below query to get result from 2 tables :
select count(age) + (select count(age)
from Table2 where age > #age)
from Table1 where age > #age
Another way
SELECT Sum(cnt) AS total
FROM (SELECT Count(age) cnt
FROM Table1
WHERE age > #age
UNION ALL
SELECT Count(age)
FROM Table2
WHERE age > #age) a
Try this #Nag
select (COUNT(t1.age) + COUNT(t2.age)) as Result
from Table1 t1
FULL JOIN Table2 t2 on t1.hvcid = t2.hvcid
where t1.age > #age and t2.age > #age
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 table with records which include a datetime column "CreationDate".
I need to get the following information for every of the last 90 days:
How many records were there in total in existence
How many records were added on that day
I could do this through a loop of counting of course, but this would hit the database 90 times... is there a better way of doing this aggregate without having to riddle the DB with requests?
I'm using C#, LINQ, SQL Server 2008.
Are you looking for something like this?
WITH CTE AS
(SELECT COUNT(*) OVER () AS TotalCount,
CAST(CONVERT(VARCHAR, CreationDate, 101) as DATETIME) as DateValue, *
FROM MyTable
WHERE CreationDate >= DATEADD(DD, -90, GETDATE())
)
SELECT DateValue, TotalCount, COUNT(*) as RowCount
FROM CTE
group by DateValue, TotalCount
order by DateValue
;
Pull the records (or just the ids and creation dates, if that is all you need), and then perform the logic in code. One SELECT against the DB.
edit
In response to comment:
You can get the number of items for each day with a query like this:
SELECT CreationDate, COUNT(CreationDate) FROM MyTable GROUP BY CreationDate
Note that this assumes no times in CreationDate. If you have different times, the grouping won't work -- you'll have to flatten those out.
You can also add a WHERE clause to only look at the items from the last 90 days.
Bringing back the daily totals for the 90 days then aggregating in your application would probably be the best idea. There is currently no particularly satisfactory way of calculating running totals in SQL Server. An example of how you could do it though is below (using sys.objects as the demo table)
IF OBJECT_ID('tempdb..#totals') IS NOT NULL
DROP TABLE #totals
DECLARE #EndDate DATE = CURRENT_TIMESTAMP;
DECLARE #StartDate DATE = DATEADD(DAY,-89,#EndDate);
WITH DateRange AS
(
SELECT
#StartDate [DATE]
UNION ALL
SELECT
DATEADD(DAY, 1, DATE) [DATE]
FROM
DateRange
WHERE
DATE < #EndDate
)
SELECT DATE,COUNT(t.modify_date) AS DailyTotal
INTO #totals
FROM DateRange LEFT JOIN sys.objects t
ON modify_date BETWEEN #StartDate AND #EndDate
AND CAST(t.modify_date AS DATE) = DateRange.Date
GROUP BY DATE
ORDER BY DATE
DECLARE #BaseNumber INT = (SELECT COUNT(*) FROM sys.objects WHERE
modify_date < #StartDate);
SELECT t1.Date,
t1.DailyTotal,
#BaseNumber + SUM(t2.DailyTotal) AS RunningTotal
FROM #totals t1
JOIN #totals t2 ON t2.date <= t1.date
/*Triangular join will yield 91x45 rows that are then grouped*/
GROUP BY t1.Date,t1.DailyTotal
ORDER BY t1.Date